正如问题所述,我试图做的是有一个函数,当从 DOM 中删除 DOM 元素时调用该函数,就像析构函数一样。
我研究了卸载,但根据我的理解,只有当浏览器导航离开页面时才会调用它。
提前致谢!
最佳答案
可以使用 special events建立移除跟踪。我创建了an example允许绑定(bind)到 removed
事件。请注意,此方法仅在 jQuery 发起删除时有效(例如调用 $(…).remove()
)。对于更通用的解决方案,请使用 DOMNodeRemoved ,但这在 IE 中不起作用。
要启用对元素的跟踪,请调用 $(…).trackRemoval()
,当您删除该元素或其父元素之一时,该元素将触发 removed
事件。
// Create a scope so that our variables are not global
(function(){
/**
* True while unbinding removal tracking
*/
var isUntracking = false;
/**
* A reference that is only known here that nobody else can play with our special event.
*/
var dummy = function(){};
/**
* Special event to track removals. This could have any name but is invoked during jQuery's cleanup on removal to detach event handlers.
*/
jQuery.event.special.elementRemoved = {
remove: function(o){
if(o.handler===dummy && !isUntracking){
$(this).trigger('removed');
}
}
};
/**
* Starts removal tracking on an element
*/
jQuery.fn.trackRemoval = function(){
this.bind('elementRemoved', dummy);
};
/**
* Stops removal tracking on an element
*/
jQuery.fn.untrackRemoval = function(){
isUntracking = true;
this.unbind('elementRemoved', dummy);
isUntracking = false;
};
})();
jsFiddle包含使用示例代码。
关于javascript - 使用 JQuery,是否可以在 DOM 元素调用 .remove() 时运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7685880/