Created
February 17, 2016 17:27
-
-
Save paulmouzas/a734b31b17a02f78433a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myElements = [ /* DOM Collection */ ]; | |
for (var i = 0; i < 100; ++i) { | |
myElements[i].onclick = function() { | |
alert( 'You clicked on: ' + i ); | |
}; | |
} | |
// That wouldn't work. By the time the element is clicked, the variable i is 99. To make this work properly we cold use a closure to capture the value of i: | |
function getHandler(n) { | |
return function() { | |
alert( 'You clicked on: ' + n ); | |
}; | |
} | |
for (var i = 0; i < 100; ++i) { | |
myElements[i].onclick = getHandler(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment