Possible Duplicate:
jQuery 1.7 - Turning live() into on()
According to the jQuery API (http://api.jquery.com/on/) the function 'live' is deprecated, it is recommended to use 'on' instead. But when I replace 'live' with 'on' in my code, jQuery can't find later added elements anymore:
This works (but is deprecated):
$('li.bibeintrag').live('click', function(){ alert('myattribute =' + $(this).attr('myattribute')); });
This is an example from the API for 'on':
$("#dataTable tbody tr").on("click", function(event){ alert($(this).text()); });
When I change my code to this ('live' replaced with 'on') it does not work anymore (jQuery will not find later added elements (e.g. with append)):
$('li.bibeintrag').on('click', function(){ alert('myattribute =' + $(this).attr('myattribute')); });
What am I doing wrong? Can someone help, please?
You should add event to any parent element of li.bibeintrag
.
$('ul').on('click', "li.bibeintrag", function(){ alert('myattribute =' + $(this).attr('myattribute')); });
jQuery's live, when viewed through the $.on
style would have looked like this:
$(document).on("click", "li.bibeintrag", function(){ });
It would listen to click events at the document
level, and determine whether their target matched the second parameter of $.on
. You and I are encouraged to do this our selves, but rather than listening at the document level, we want to listen much closer to the element itself (so the event doesn't need to propagate too far before it's handled).
Since you're responding to clicks on an li
, listen at the level of that items parent:
$("ul#myList").on("click", "li.bibeintrag", function(){ /* Respond */ });
Keep in mind that without providing the second parameter of $.on
, the event handler is bound to the element itself, meaning you don't get the behavior of $.live
which would react to dynamically added elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With