Reputation: 7969
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>
Upvotes: 3
Views: 351
Reputation: 29186
Change this -
$("a.myLink").on('click', function() { alert( 'Click!' ); } );
to this -
$(document).on('click', 'a.myLink', function(){ alert( 'Click!' ); } );
Upvotes: 1
Reputation: 3198
Your clue is that it works with the live method. It works then because you are adding the class to '#another' after already setting the event. So you either have to use the live method or switch the order so that the class is added to 'another' first.
Upvotes: 0
Reputation: 1636
Try
$(document).on('click', 'a.mylink', function() { alert( 'Click!' ); } );
Upvotes: 1
Reputation: 708196
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!' ); } );
Upvotes: 3