Skip to content

Instantly share code, notes, and snippets.

@flipflop
Created September 25, 2011 11:58
Show Gist options
  • Save flipflop/1240536 to your computer and use it in GitHub Desktop.
Save flipflop/1240536 to your computer and use it in GitHub Desktop.
JavaScript Closure to correct lost scope
<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