Reputation: 25475
Could you please have a quick look at the sample code
I don't know if its clear, but what it's supposed to do is show what i
was when the event was created. Instead what I think it's doing is showing the value of i
when the event is fired.
How would I solve my issue?
Upvotes: 3
Views: 3319
Reputation: 349262
Wrap the loop's body in a function, to create a closure:
for(var i = 0; i < arr.length; i++){
(function(i){ //i inside this function is a local var; not affected by i++
arr[i].onclick = function(){
alert(i);
return false;
};
})(i); //Invoke the function, pass variable i
}
Fiddle: http://jsfiddle.net/vXvs2/4/
Upvotes: 6