我试图弄清楚如何执行一些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特殊事件。

简单地说,

设置:

(function($){
  $.event.special.destroyed = {
    remove: function(o) {
      if (o.handler) {
        o.handler()
      }
    }
  }
})(jQuery)

用法:

$('.thing').bind('destroyed', function() {
  // do stuff
})

回答Pierre和DesignerGuy评论的附录:

要在调用$('.thing').off('destroyed')时不触发回调,请将if条件更改为:if (o.handler && o.type !== 'destroyed'){…}

其他回答

我不能得到这个答案与解绑定工作(尽管更新见这里),但能够想出一个办法。答案是创建一个“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++;
});

这里有一把小提琴

挂钩.remove()并不是最好的处理方法,因为有很多方法可以从页面中删除元素(例如,通过使用.html(), .replace()等)。

为了防止各种内存泄漏危险,jQuery将在内部尝试为每个被删除的元素调用jQuery. cleandata()函数,而不管使用什么方法来删除它。

查看这个答案了解更多细节:javascript内存泄漏

所以,为了得到最好的结果,你应该钩子cleanData函数,这正是jquery.event.destroyed插件所做的:

http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js

参考@David的回答:

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

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

这是如何创建一个jQuery实时删除监听器:

$(document).on('DOMNodeRemoved', function(e)
{
  var $element = $(e.target).find('.element');
  if ($element.length)
  {
    // do anything with $element
  }
});

Or:

$(document).on('DOMNodeRemoved', function(e)
{
  $(e.target).find('.element').each(function()
  {
    // do anything with $(this)
  }
});

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元素被删除。