我试图弄清楚如何执行一些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.type !== 'destroyed'){…}