3

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>
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • Before you use `on`, do some study on *event delegation* and then read the docs. It's an important technique to understand in general. –  Mar 22 '12 at 05:25

4 Answers4

3

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!' ); } );
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Try

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

LeeR
  • 1,609
  • 11
  • 29
  • 2
    Attaching many delegated event handlers near the top of the document tree can degrade performance. For best performance, attach delegated events at a document location as close as possible to the target elements. ( http://api.jquery.com/on/ ) – Alex Mar 22 '12 at 05:22
1

Change this -

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

to this -

$(document).on('click', 'a.myLink', function(){ alert( 'Click!' ); } );
MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
0

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.

Mark Fraser
  • 3,160
  • 2
  • 29
  • 48