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

当前回答

参考@David的回答:

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

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

其他回答

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

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

参考@David的回答:

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

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

我们也可以使用domnodermoved:

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

为此,可以使用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/