SHi
SHi

Reputation: 23

Calling an specific Array of Functions

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.

Upvotes: 1

Views: 29

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386634

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>

Upvotes: 3

Mahi
Mahi

Reputation: 1727

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]();

Upvotes: 1

Related Questions