JQuery: how to replace .live with .on?

Possible duplicate:
jQuery 1.7 - Enabling Live () in on ()

According to the jQuery API ( http://api.jquery.com/on/ the "live" function is deprecated, it is recommended to use 'on' instead, But when I replace 'live' with 'on' in my code, jQuery can no longer find later added items:

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' is replaced by 'on'), it no longer works (jQuery will not find later added elements (for example, with an addition)):

 $('li.bibeintrag').on('click', function(){ alert('myattribute =' + $(this).attr('myattribute')); }); 

What am I doing wrong? Can someone help please?

+45
jquery
May 15 '12 at 15:47
source share
3 answers

You must add an event to any parent element of li.bibeintrag .

 $('ul').on('click', "li.bibeintrag", function(){ alert('myattribute =' + $(this).attr('myattribute')); }); 
+63
May 15 '12 at 15:47
source share

jQuery live, if you look through the $.on style, would look like this:

 $(document).on("click", "li.bibeintrag", function(){ }); 

It will listen for click events at the document level and determine if their purpose matches the second parameter of $.on . We encourage you to do this ourselves, but instead of listening to the level of the document, we want to get to know the element itself much more closely (so the event should not spread too far before it is processed).

Since you are responding to clicks on li , listen at the parent level:

 $("ul#myList").on("click", "li.bibeintrag", function(){ /* Respond */ }); 

Keep in mind that without providing the second parameter $.on event handler is bound to the element itself, that is, you will not get $.live behavior that will respond to dynamically added elements.

+29
May 15, '12 at 15:50
source share

This should work

 $('ul').on('click','li.bibeintrag' function(){ alert('myattribute =' + $(this).attr('myattribute')); }); 
0
May 15 '12 at 15:51
source share



All Articles