4 ms·
I think they all alert '3' because of the missing 'var' keyword.
by austintaylor 16y ago
I think they all alert '3' because of the missing 'var' keyword.
- watmough 16y agoThis is my thought also, but I'm unsure of how to lock in the correct integer value to the alert, such that clicking each li element pops up the correct number. I'm guessing one would have to create an object with a scope that holds the right value, on each turn through the loop.
- bcrescimanno 16y agoYou're on the right track; they'll all print 4; but it's not because of the missing var keyword.
- mustpax 16y agoJust adding var wouldn't be enough, you're still referencing the variable from the outer scope. You need to create your own copy. Instead of: 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 :)
- SMrF 16y agoI think you want var j = i outside the function. Edit: Oops, this is wrong as well. :-)
- tremendo 16y agoalert('"'+i+'"')
- theoretical 16y agoThat won't quite work, as you're still just copying the value of i when that function is executed, which will be 4. 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 http://news.ycombinator.com/item?id=2124559
- deleted 16y ago[deleted]
- archgoon 16y agoThat won't work either. You're still setting the variable to the global variable i. The only way I can think of doing this is as follows 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 http://news.ycombinator.com/item?id=2124532
- mumrah 16y agoI create a closure outside of the event registration: http://pastebin.com/igzWkgKF http://pastebin.com/igzWkgKF
- Timmy_C 16y agoIf you run the code you'll find that they all alert('4'). However, the third parameter of els.addEventListener() so you'll get an exception if you run the code verbatim.
- emehrkay 16y agoThats not the reason why it will alert 3 (it will alert 4, btw). Here is a fix http://jsfiddle.net/hBe3c/ http://jsfiddle.net/hBe3c/