jQuery remove() callback?

2019-01-11 23:00发布

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

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.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-11 23:35

you can use jQuery.when():

$.when($('div').remove()).then( console.log('div removed') );
查看更多
女痞
3楼-- · 2019-01-11 23:41

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
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-11 23:50

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

$('div').hide(1, function(){
    // callback
    $(this).remove();
});
查看更多
登录 后发表回答