I think they all alert '3' because of the missing 'var' keyword.
els[i].addEventListener('click', function(){alert(i);});
Do: els[i].addEventListener('click',
function() {
var j = i;
alert(j);
});
Edit: This is wrong, archgoon has the correct answer below. That'll teach me for jumping on closure problems in the morning :)els[i].addEventListener('click',function(k){function(){alert(k)}}(i));
EDIT: See lhorie's suggestion below for a much cleaner way of doing this. http://news.ycombinator.com/item?id=2124532
You could make the function take a parameter, then return a function which uses that parameter, or use currying.
Edit: I've posted a working version in my comment further down, http://news.ycombinator.com/item?id=2124559
Edit: Oops, this is wrong as well. :-)
Here is a fix http://jsfiddle.net/hBe3c/
I'm guessing one would have to create an object with a scope that holds the right value, on each turn through the loop.