Passing Parameters to a Function on HTML Events

Let’s say I have some function foo that needs to be called when some HTML element is clicked:

function foo(a, b) {
    :
    :
    :
}

:

i = 100;
j = 200;
element.setAttribute("onclick", "foo(i, j)");

In the example above, the Javascript interperter will see the line element.setAttribute("onclick", "foo(i, j)"); and automatically figure out that i and j should be 100 and 200, respectively.

However, the same doesn’t work if you’re working with arrays indicies:

bar = new Array();
bar[0] = 100;
bar[1] = 200;
element.setAttribute("onclick", "foo(bar[0], bar[1])");

To work around it, I had to re-assign them to variables:

bar = new Array();
bar[0] = 100;
bar[1] = 200;

i = bar[0];
j = bar[1];
element.setAttribute("onclick", "foo(i, j)");

That definitely made me go…hunh??

This entry was posted in Javascript, Tech and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>