我想弄清楚如何在从页面中删除元素时执行一些 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 特殊事件。
简单来说,
设置:
(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.输入 !== 'destroyed') { ... }
关于jQuery - 当元素从 DOM 中移除时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2200494/