Asperger Asperger - 4 years ago 152
Javascript Question

Javascript what is "index" within an argument?

var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{

(function(index){
g.children[i].onclick = function(){
alert(index) ;
}
})(i);

}


So I saw the above example that shows how to get the index of the clicked element. I noticed that it uses "index" as a parameter. Unfortunately I am only aware of indexof so how does this work? I cant find anything about "index" when googling: javascript index property or javascript index argument.

Edit: I really didnt see the function call with (i) as it was so small.

Answer Source

The other answer and comments are correct, index in this case is just a function argument, but I'll (try) to explain a bit more what's going on here.

As others have said, index is just a variable, in this case the argument to the function. There's nothing special about the name index here, it could have been argument1 or vader :-), or whatever.

So what's happening is that this function is being declared:

function(arg1){
        g.children[i].onclick = function(){
              alert(arg1)  ;
        }    
    }

I've replaced index with arg1 to show that index isn't special, although it works fine with index. After that function's declared, it's being called by wrapping it in parens, and then passing the argument i (the (i)). This calls the function, assigning the current value of i to the first argument to the function, arg1 here, or index in the original. The function declares another function, this time

function() {alert(arg1);}

and assigns it to the onclick handler of the i'th element of the g.children array. So each onclick handler will be a function that just does an alert of the index of the array element.

If you step through the loop in a debugger, you'll see it effectively does:

g.children[0].onclick = function(){ alert(0); };
g.children[1].onclick = function(){ alert(1); };
g.children[2].onclick = function(){ alert(2); };

etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download