我试图弄清楚如何执行一些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
});

当前回答

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

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

其他回答

我喜欢mtkopone使用jQuery特殊事件的答案,但请注意,它不能工作a)当元素被分离而不是删除或b)当一些旧的非jQuery库使用innerHTML破坏你的元素

jQuery的“remove”事件工作正常,没有添加。它可能是更可靠的使用一个简单的技巧,而不是补丁jQuery。

只需在要从DOM中删除的元素中修改或添加一个属性。因此,您可以使用属性“do_not_count_it”触发任何更新函数,该函数将忽略正在被销毁的元素。

假设我们有一个表格,单元格对应的价格,你只需要显示最后的价格: 这是在价格单元格被删除时触发的选择器(我们在表格的每一行中都有一个按钮,这里没有显示)

$('td[validity="count_it"]').on("remove", function () {
    $(this).attr("validity","do_not_count_it");
    update_prices();
});

这里有一个函数查找表中最后一个价格,不考虑最后一个价格,如果它是被删除的价格。实际上,当"remove"事件被触发,并且当这个函数被调用时,元素还没有被删除。

function update_prices(){
      var mytable=$("#pricestable");
      var lastpricecell = mytable.find('td[validity="count_it"]').last();
}

最后,update_prices()函数正常工作,然后,DOM元素被删除。

你可以绑定到DOMNodeRemoved事件(DOM Level 3 WC3规范的一部分)。

适用于IE9,最新版本的Firefox和Chrome。

例子:

$(document).bind("DOMNodeRemoved", function(e)
{
    alert("Removed: " + e.target.nodeName);
});

您还可以通过绑定到DOMNodeInserted来获得元素插入时的通知

没有用于删除元素的内置事件,但是可以通过伪扩展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

参考@David的回答:

当你想做soo与另一个函数,例如。Html()就像在我的情况下,不要忘记在新函数中添加return:

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