Skip to content

Instantly share code, notes, and snippets.

@eligundry
Created June 13, 2012 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligundry/2926057 to your computer and use it in GitHub Desktop.
Save eligundry/2926057 to your computer and use it in GitHub Desktop.
Better way of attaching event listeners
<ul>
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
<li id="item-3">Item 3</li>
</ul>
<script type="text/javascript">
$('ul').on('click', 'li', function(e) {
alert( "You clicked " + $(this).text() );
});
</script>
<ul>
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
<li id="item-3">Item 3</li>
</ul>
<script type="text/javascript">
for ( var i = 1; i <= 3; i ++ ) {
(function(i) {
$('#item-' + i).click(function() {
alert('You clicked item ' + i);
});
}(i));
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment