Skip to content

Instantly share code, notes, and snippets.

@miku
Created January 21, 2011 00:22
Show Gist options
  • Save miku/789011 to your computer and use it in GitHub Desktop.
Save miku/789011 to your computer and use it in GitHub Desktop.
<html>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
</ul>
</body>
<script type="text/javascript">
// http://cam.ly/blog/2011/01/javascript-interview-question/
// els = document.getElementsByTagName('li');
// for(i=0; i < els.length; i++){
// els[i].addEventListener('click', function(){alert(i);}, false);
// }
// VERSUS
function getHandler(i) {
return function() { alert(i); }
}
els = document.getElementsByTagName('li');
for(i = 0; i < els.length; i++){
els[i].addEventListener('click', getHandler(i), false);
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment