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

其他回答

我们也可以使用domnodermoved:

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

刚刚检查过,它已经内置在当前版本的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/

只需要jQuery(不需要jQuery UI)

(我已经从jQuery UI框架中提取了这个扩展)

适用于:empty()和html()和remove()

$.cleanData = ( function( orig ) {
    return function( elems ) {
        var events, elem, i;
        for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
            try {

                // Only trigger remove when necessary to save time
                events = $._data( elem, "events" );
                if ( events && events.remove ) {
                    $( elem ).triggerHandler( "remove" );
                }

            // Http://bugs.jquery.com/ticket/8235
            } catch ( e ) {}
        }
        orig( elems );
    };
} )( $.cleanData );

使用此解决方案,还可以解除事件处理程序的绑定。

$("YourElemSelector").off("remove");

试一试!——示例

$.cleanData = (function(orig) { return function(elems) { var events, elem, i; for (i = 0; (elem = elems[i]) != null; i++) { try { // Only trigger remove when necessary to save time events = $._data(elem, "events"); if (events && events.remove) { $(elem).triggerHandler("remove"); } // Http://bugs.jquery.com/ticket/8235 } catch (e) {} } orig(elems); }; })($.cleanData); $("#DivToBeRemoved").on("remove", function() { console.log("div was removed event fired"); }); $("p").on("remove", function() { console.log("p was removed event fired"); }); $("span").on("remove", function() { console.log("span was removed event fired"); }); // $("span").off("remove"); $("#DivToBeRemoved").on("click", function() { console.log("Div was clicked"); }); function RemoveDiv() { // $("#DivToBeRemoved").parent().html(""); $("#DivToBeRemoved").remove(); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3> <div class="container"> <br> <button onclick="RemoveDiv();">Click here to remove div below</button> <div id="DivToBeRemoved"> DIV TO BE REMOVED contains 1 p element which in turn contains a span element <p>i am p (within div) <br><br><span>i am span (within div)</span></p> </div> </div>

附加演示- jsBin

我不确定是否有此事件句柄,因此您必须保留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");

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

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

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

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

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