Skip to content

Instantly share code, notes, and snippets.

@EvanKrall
Created March 1, 2011 08:20
Show Gist options
  • Save EvanKrall/848811 to your computer and use it in GitHub Desktop.
Save EvanKrall/848811 to your computer and use it in GitHub Desktop.
Closures and for loops.
<html>
<head>
<style>
span {
border: 1px solid black;
border-radius: 6px;
padding: 3px;
margin: 2px;
background: #dde;
-webkit-box-shadow: 3px 3px 6px rgba(0,0,0,0.5);
}
</style>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
buttons = $('.button');
for (var i=0; i<buttons.length; i++) {
buttons[i].onclick = function() {
alert(i);
};
}
$('#fixit').click(function() {
buttons = $('.button');
for (var i=0; i<buttons.length; i++) {
buttons[i].onclick = (function(i) {
return function() {
alert(i)
}
}(i));
}
})
});
</script>
</head>
<body>
<span class="button">Button!</span>
<span class="button">Button!</span>
<span class="button">Button!</span>
<span class="button">Button!</span>
<span class="button">Button!</span>
<span id="fixit">Fix them.</span>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment