i
will not contain the "current index" like you are intending, but rather the last value i
was, ie arr.length
One quick n dirty solution would be to do something like this
for(var i = 0; i < arr.length; i++) {
(function(_i){
arr[_i].onclick = function() { alert(arr[_i].innerHTML); };
})(i);
}
what this does is captures the current value of i
in a new variable _i
within the closure of the statement you're executing, so it'll stay around and be the value you'd expect every time your onclick handler is called.