What is the most effective solution for addressing this issue related to closure in JavaScript?
Here is a simple problem I am facing:
I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click):
var spans = document.getElementsByTagName('span');
function addEvents(divs) {
for(var i=0; i < divs.length; i++) {
divs[i].innerHTML = i;
divs[i].onclick = function() { alert(i) };
}
}
addEvents(spans);
You can also view the code in action on JSFiddle.