1

I want to call an specific array of function on my onclick.

Example JS:

var foo = [
  function() { alert("Function 1!"); },
  function() { alert("Function 2!"); }
];

Example HTML:

<a onclick="foo[0]" >Alert</a>

but dont understand how get it done.

2 Answers 2

3

You need parenthesis for calling the function. Otherwise you return the function itself, like in example 2.

<a onclick="foo[0]()" >Alert</a>
<!--              ^^         -->

var foo = [
    function() { alert("Function 1!"); },
    function() { alert("Function 2!"); }
];
<a onclick="foo[0]()" >Alert</a><br>
<a onclick="alert(foo[0])" >Alert, what really happens without parenthesis</a>

Sign up to request clarification or add additional context in comments.

1 Comment

as plain as the nose on your face, stupid me and thanks a lot :)
1

you should call the function . since you are getting only function using foo[0] . you need to call them by () to run the function

var foo = [
  function() { alert("Function 1!"); },
  function() { alert("Function 2!"); }
];
foo[0]();
foo[1]();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.