i have 2 lines jquery. first line is adding event on "myLink" and second line adding class "myLink" on "#another" but event is not working in second one but when i am using .live method then it is wokring. jquery introduce .on method in its 1.7 version. i want to do that it by .in function is this possible.
$(function(){
$("a.myLink").on('click', function() { alert( 'Click!' ); } );
$("a#another").addClass( "myLink" );
})
<a class="myLink">A link!</a>
<a id="another">Another link!</a>
I just wrote a primer on using .on() to replace .live() and explained both the static form of .on() (which you are using) and the dynamic form of .on() (which you need to be using). That primer from earlier today is here: Does jQuery.on() work for elements that are added after the event handler is created? which contains a lot more of the details.
You need to use something like this:
$(document).on('click', "a.myLink" function() { alert( 'Click!' ); } );
or, even better use a static ancestor of your dynamic links instead of document (which I will assume here is an object #container as this will give better performance like this:
$("#container").on('click', "a.myLink" function() { alert( 'Click!' ); } );
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