开发者

How do I get event listeners to recognize new document elements?

开发者 https://www.devze.com 2023-03-10 04:30 出处:网络
How can I get jQuery event listeners to listen to elements loaded through ajax calls? I load comments into my document via ajax. Each comment has an ajax delete button. For comments that were loaded

How can I get jQuery event listeners to listen to elements loaded through ajax calls?

I load comments into my document via ajax. Each comment has an ajax delete button. For comments that were loaded originally with the document, my function works fine.

But any newly created comments, or comments retrieved through ajax, the event lister does not pick-up on them.

<a class="comment-delete" href="/comments/delete/124">delete</a>

$(".comment-delete").click(function(e) {
    e.preventDefault();

    var $link = $(this),
        url = $link.attr('href');

        $.ajax(url, {
            dataType: 'json',
            beforeSend: function() {
            },
            error: function() {
            },
            success: function(data) {
                if (data.success) {
                    $($link).parent().parent().hide();
                }
            }
        });开发者_Python百科
});


Updated Answer

Today, the appropriate way to do this is to use the on method with an additional selector. For instance, if we wanted to listen for any click on images we could do this:

$("img").on("click", function () {
    alert( "You clicked on " + this.src );
});

This will not work for any image elements added to the DOM after this code was ran. Instead, we need to use event delegation, meaning we handle the event further up the DOM in its bubbling phase:

$(document).on("click", "img", function () {
    alert( "You clicked on " + this.src );
});

In this case, we handle the event at the document level, but only if the element it proceeded from matches our second "img" selector. So any image, whether it was on the page initially, or dynamically loaded in at a later time, will now be handled.

Original Answer (Written in 2011)

$.live() and $.delegate() are the two methods you should be looking to. The first will listen to the document for any new elements matching your selector, and the second will provide a more granular scope for where it ought to be listening.

$(".comment-delete").live("click", function(){
  // handle delete logic
});

Or, the more specific:

$(".comments").delegate(".comment-delete", "click", function(){
  // handle delete logic
});


You're looking for live http://api.jquery.com/live/

0

精彩评论

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