Skip to content

Instantly share code, notes, and snippets.

@paulmouzas
Created February 17, 2016 17:27
Show Gist options
  • Save paulmouzas/a734b31b17a02f78433a to your computer and use it in GitHub Desktop.
Save paulmouzas/a734b31b17a02f78433a to your computer and use it in GitHub Desktop.
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