Created
June 13, 2012 19:49
-
-
Save eligundry/2926057 to your computer and use it in GitHub Desktop.
Better way of attaching event listeners
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 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> |
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 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