Jquery.on function?

I have 2 lines of jquery. the first line adds an event to "myLink" and the second line adds the class "myLink" to "#another", but the event doesn't work in the second, but when I use the .live method it wokring. jquery introduces the .on method in its 1.7 version. I want to do it over the .in function. It is 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>

      

+3


source to share


4 answers


I just wrote a tutorial on how .on()

to use to replace .live()

and explained both the static form .on()

(which you are using) and the dynamic form .on()

(which you should be using). This primer from today is here: Does jQuery.on () work for elements that are added after creating an event handler? which contains a lot more detail.

You need to use something like this:

$(document).on('click', "a.myLink" function() { alert( 'Click!' ); } );

      



or even better to use the static ancestor of your dynamic links instead document

(which I will think of as an object here #container

, as it will give better performance like this:

$("#container").on('click', "a.myLink" function() { alert( 'Click!' ); } );

      

+3


source


Try



$(document).on('click', 'a.mylink', function() { alert( 'Click!' ); } );

+1


source


Change this -

$("a.myLink").on('click', function() { alert( 'Click!' ); } );

      

for this -

$(document).on('click', 'a.myLink', function(){ alert( 'Click!' ); } );

      

+1


source


Your hint is that it works with a live method. It works then because you add the class to "#another" after you've already set the event. So you either need to use a live method or switch the order to add the class to "other" first.

0


source







All Articles