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

当前回答

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

这里有一把小提琴

其他回答

这一点。

$.each(
  $('#some-element'), 
        function(i, item){
            item.addEventListener('DOMNodeRemovedFromDocument',
                function(e){ console.log('I has been removed'); console.log(e);
                })
         })

为此,可以使用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'){…}

刚刚检查过,它已经内置在当前版本的JQuery中:

jQuery - v1.9.1

jQuery UI - v1.10.2

$("#myDiv").on("remove", function () {
    alert("Element was removed");
})

重要:这是Jquery UI脚本(不是Jquery)的功能,所以你必须加载两个脚本(Jquery和Jquery - UI)使其工作。例如:http://jsfiddle.net/72RTz/

我们也可以使用domnodermoved:

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

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