Javascript jQuery remove() 回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7594817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:50:56  来源:igfitidea点击:

jQuery remove() callback?

javascriptcallbackjquery

提问by chroder

Is there an official way to hook in to jQuery.remove() so that a function can be called before/after?

是否有一种官方方法可以连接到 jQuery.remove() 以便可以在之前/之后调用函数?

I have a system whereby certain handlers are attached to elements, and sometimes these elements are removed (eg. a UI widget whose primary element is removed by some other action on the page). If handlers could be notified that their primary element was removed, I can run cleanup routines a little easier.

我有一个系统,其中某些处理程序附加到元素,有时这些元素会被删除(例如,一个 UI 小部件,其主要元素被页面上的某些其他操作删除)。如果可以通知处理程序其主要元素已被删除,我可以更轻松地运行清理例程。

回答by mcnesium

you can use jQuery.when():

你可以使用jQuery.when()

$.when($('div').remove()).then( console.log('div removed') );

回答by Drew

Use a custom event, attach handlers to the custom event that fire before/after the remove. For example,

使用自定义事件,将处理程序附加到在删除之前/之后触发的自定义事件。例如,

$( document ).bind( 'remove', function( event, dom ){

    $( document ).trigger( 'beforeRemove', [ dom ] );
    $( dom ).remove();
    $( document ).trigger( 'afterRemove', [ dom ] );
});

$( document ).trigger( 'remove', 'p' ); //Remove all p's

回答by Kenneth Palaganas

Here's a nifty hack - you might wanna give it a try.

这是一个漂亮的黑客 - 你可能想试一试。

$('div').hide(1, function(){
    // callback
    $(this).remove();
});