Your event handler function has an enduring reference to i
, not a copy of its value, as you've discovered.
To prevent that, have the function close over something else that won't change:
for(var i=1;i<9;i++){
document.getElementById('element'+i).onclick=makeHandler(i);
}
function makeHandler(index) {
return function() {
theFunc(index);
};
}
makeHandler
creates a function that closes over index
, which is a copy of the value of i
, and so doesn't change as the loop continues. Each event handler gets its own index
.
That said, creating a bunch of event handler functions that are effectively identical usually means you can redesign a bit and use just one handler function. In this case, for instance, you could do this:
for(var i=1;i<9;i++){
document.getElementById('element'+i).onclick=theHandler;
}
function theHandler() {
func(parseInt(this.id.replace(/\D/g, ''));
}
...which grabs the value to use from the id
of the element.
Another approach is delegation, where you actually hook the click
event on an ancestor element (one that all of these elementX's have in common), and then when the click occurs, look at event.target
and its ancestors to see what you should do.