1
$('.kkk').click(function() {
  // Execute Event
});

$('body').append('<div class="kkk">Another target</div>');

Since it was added after the call to .click(), clicks on it will do nothing.

A> I wonder if Any way to trigger the handler(click) added later? except live()

Thank you~~~~

Dustin Laine
  • 37,935
  • 10
  • 86
  • 125
SoonYeoung
  • 43
  • 1
  • 1
  • 6

2 Answers2

1

delegate() is exactly what you need for this. live() should be deprecated, in my opinion.

$("body").delegate(".kkk", "click", function() {

    // Execute Event

});

EDIT : Seeing as how there's some discussion over live() vs delegate(), take a look at the posted answer to this question: Jquery live() vs delegate(). I think it's pretty clear.

Community
  • 1
  • 1
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
  • delegate and live serve slightly different purposes... There's room and use cases to support having both in jQuery. – Endophage Apr 27 '11 at 23:07
  • Delegate() is much, much more efficient than live(). – Code Maverick Apr 27 '11 at 23:09
  • Not when you're binding to the body. It would be more efficient if you were using it in the context of some much deeper element. – Endophage Apr 27 '11 at 23:17
  • I agree. That would be the OP's job to narrow it down. I don't know their markup. – Code Maverick Apr 27 '11 at 23:18
  • Thank you! Scott. I did it. this is what i'm looking for – SoonYeoung Apr 27 '11 at 23:33
  • Also, don't forget to change `$("body")` to something more narrowed down. For example if all of your `".kkk"` classes are in a div, you could use `$("div")` or if they are all inside of a div with `id="content"`, you could use `$("#content", "div")`. Basically, try to use the most narrowed down selector you can to improve performance. – Code Maverick Apr 27 '11 at 23:44
1
$('.kkk').live('click',function() {
  // Execute Event
});

$('body').append('<div class="kkk">Another target</div>');

using live will match all future elements written to the page as well as those that exist when the event is "bound".

UPDATE:

jQuery as of 1.7 has deprecated live (and bind) in favour of using on with delegated events. To use a delegated event, you attach on to an element that will exist on the page at load, then filter by a selector that will exist later. For example:

$('body').on('click', '.kkk', function(){
    // Execute Event
});

$('body').append('<div class="kkk">Another target</div>');

If the element will exist on the page when document onload is fired, you can simply attach it as:

$('body .kkk').on('click', function(){
    // Execute Event
});
Endophage
  • 21,038
  • 13
  • 59
  • 90