我试图弄清楚如何执行一些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(不需要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
挂钩.remove()并不是最好的处理方法,因为有很多方法可以从页面中删除元素(例如,通过使用.html(), .replace()等)。
为了防止各种内存泄漏危险,jQuery将在内部尝试为每个被删除的元素调用jQuery. cleandata()函数,而不管使用什么方法来删除它。
查看这个答案了解更多细节:javascript内存泄漏
所以,为了得到最好的结果,你应该钩子cleanData函数,这正是jquery.event.destroyed插件所做的:
http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js