3 ms·
Does 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: v
by kenjackson 16y ago
Does 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