Created
September 25, 2011 11:58
-
-
Save flipflop/1240536 to your computer and use it in GitHub Desktop.
JavaScript Closure to correct lost scope
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
<ul> | |
<li>item One</li> | |
<li>item Two</li> | |
<li>item Three</li> | |
</ul> | |
<script> | |
var listElements = document.getElementsByTagName("li"); | |
for(var i=0; i < listElements.length; i++) { | |
// without closure i equals the last iteration of loop for each onclick | |
(function(inc) { | |
listElements[inc].onclick = function() { | |
alert(inc); | |
}; | |
}(i)); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment