This is probably an easy question but I can\'t figure out the best answer for it.
I have 10 cli
You only have one variable i
in an outer scope shared by all your click handlers. You need to create a local variable i
for each closure. This will work:
for ( var i = 0; i < 10; i++ ) {
var element = document.getElementById( "element" + i );
element.onclick = (function(i){
// returns a new function to be used as an onclick handler
return function () {
alert( "Element " + i );
}
})(i); // Pass in the value of the outer scope i
}
Check "The Infamous Loop" problem in this article (and read the whole artice) for more information :)