3 ms·
this is what I usually tell people to do: var els = document.getElementsByTagName('li');//use var unless you really really really meant global for(var i=0;
by lhorie 16y ago
this is what I usually tell people to do:
var els = document.getElementsByTagName('li');//use var unless you really really really meant global
for(var i=0; i < els.length; i++){
(function(i) {//creates new scope for each iteration
els[i].addEventListener('click', function(){alert(i);}, false);
})(i);
}
- aaronblohowiak 16y agoi agree with the choice of code, but I have a different style for laying out the code. i dislike the declaration and immediate execution of an anonymous function. i much prefer to give it a name, move it out of the loop itself and then call it within the loop. it makes reading the code more top-to-bottom. with this approach, when I get to the anon func declaration, i have to scan down looking for when it is invoked. while indentation helps, i then have to backtrack up to the beginning of the func declaration.. and hopefully i haven't lost track of what the execution context for the anon func is and so forth...
- lhorie 16y agoI don't generally care too much to talk about style when the problem at hand is that someone has been banging their head against the desk for the past two hours and they just want it to work (and, in my experience, this usually is the case, for some reason) But yeah, if we're gonna be super nitpicky, yeah sure, improve the for loop also, while we're at it. for (var i = -1; els[++i];) {//given the code in the loop body, this is shorter and faster
- kenjackson 16y agoDoes this work (from a non-JS person -- I like reading JS books, but don't code in it at all). This is certainly less elegant, but seems easier to follow: var els = document.getElementsByTagName('li'); for(i=0; i < els.length; i++){ var j = i; els[j].addEventListener('click', function(){alert(j);}, false); }
- buerkle 16y agoThat doesn't work. Variables in javascript are not block scoped but function scoped.
- kenjackson 16y agoThanks. Good to know.
- lhorie 16y agoNo, it doesn't because j is in the same scope as i. Your confusion is because of a javascript quirk for (...) { var foo = bar } is actually the same as var foo for (...) { foo = bar } Notice how you only ever have one foo What you need is: for (...) { (function(bar) { var foo = bar })(bar) } which create a new foo every time you loop