我试图弄清楚如何执行一些js代码时,一个元素从页面删除:

jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */

有没有专门的活动,比如:

jQuery('#some-element').onremoval( function() {
    // do post-mortem stuff here
});

当前回答

对于那些使用jQuery UI的人:

jQuery UI已经覆盖了一些jQuery方法来实现remove事件,该事件不仅在你显式删除给定元素时被处理,而且在元素被任何自清理jQuery方法(例如replace, html等)从DOM中删除时也会被处理。这基本上允许您在jQuery“清理”与DOM元素相关的事件和数据时,将钩子放入相同的事件中。

John Resig表示,他愿意在未来版本的jQuery核心中实现这个事件,但我不确定它目前的位置。

其他回答

没有用于删除元素的内置事件,但是可以通过伪扩展jQuery的默认删除方法来创建一个事件。注意,必须在实际删除回调以保持引用之前调用回调。

(function() {
    var ev = new $.Event('remove'),
        orig = $.fn.remove;
    $.fn.remove = function() {
        $(this).trigger(ev);
        return orig.apply(this, arguments);
    }
})();

$('#some-element').bind('remove', function() {
    console.log('removed!');
    // do pre-mortem stuff here
    // 'this' is still a reference to the element, before removing it
});

// some other js code here [...]

$('#some-element').remove();

注意:这个答案的一些问题已经被其他的帖子概括出来了。

当通过html() replace()或其他jQuery方法删除节点时,这将不起作用 这个事件出现了 jQuery UI覆盖删除以及

这个问题最优雅的解决方案似乎是:https://stackoverflow.com/a/10172676/216941

我不能得到这个答案与解绑定工作(尽管更新见这里),但能够想出一个办法。答案是创建一个“destroy_proxy”特殊事件,触发一个“destroyed”事件。你把事件监听器放在'destroyed_proxy'和'destroyed'上,然后当你想解除绑定时,你只需要解除'destroyed'事件的绑定:

var count = 1;
(function ($) {
    $.event.special.destroyed_proxy = {
        remove: function (o) {
            $(this).trigger('destroyed');
        }
    }
})(jQuery)

$('.remove').on('click', function () {
    $(this).parent().remove();
});

$('li').on('destroyed_proxy destroyed', function () {
    console.log('Element removed');
    if (count > 2) {
        $('li').off('destroyed');
        console.log('unbinded');
    }
    count++;
});

这里有一把小提琴

亚当的答案的扩展,以防你需要防止违约,这里有一个工作:

$(document).on('DOMNodeRemoved', function(e){
        if($(e.target).hasClass('my-elm') && !e.target.hasAttribute('is-clone')){
            let clone = $(e.target).clone();
            $(clone).attr('is-clone', ''); //allows the clone to be removed without triggering the function again

            //you can do stuff to clone here (ex: add a fade animation)

            $(clone).insertAfter(e.target);
            setTimeout(() => {
                //optional remove clone after 1 second
                $(clone).remove();
            }, 1000);
        }
    });

我们也可以使用domnodermoved:

$("#youridwhichremoved").on("DOMNodeRemoved", function () {
// do stuff
})

我不确定是否有此事件句柄,因此您必须保留DOM的副本,并在某种轮询循环中与现有DOM进行比较——这可能相当麻烦。Firebug可以做到这一点——如果您检查HTML并运行一些dom更改,它会在Firebug控制台中以黄色高亮显示更改。

或者,你可以创建一个删除函数…

var removeElements = function(selector) {
    var elems = jQuery(selector);

    // Your code to notify the removal of the element here...
    alert(elems.length + " elements removed");

    jQuery(selector).remove();
};

// Sample usage
removeElements("#some-element");
removeElements("p");
removeElements(".myclass");