开发者

Any way to trigger the handler added later?

开发者 https://www.devze.com 2023-03-01 17:18 出处:网络
$(\'.kkk\').click(function() { // Execute Event }); $(\'body\').append(\'<div class=\"kkk\">Another target</div>\');
$('.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~开发者_JAVA技巧~~~


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.


$('.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
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号