jQuery - Trigger event when an element is removed from the DOM

前端 未结 16 1808
面向向阳花
面向向阳花 2020-11-22 17:29

I\'m trying to figure out how to execute some js code when an element is removed from the page:

jQuery(\'#some-element\').remove(); // remove some element fr         


        
16条回答
  •  失恋的感觉
    2020-11-22 17:36

    I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:

    var count = 1;
    (function ($) {
        $.event.special.destroyed_proxy = {
            remove: function (o) {
                $(this).trigger('destroyed');
            }
        }
    })(jQuery)
    
    $('.remove').on('click', function () {
        $(this).parent().remove();
    });
    
    $('li').on('destroyed_proxy destroyed', function () {
        console.log('Element removed');
        if (count > 2) {
            $('li').off('destroyed');
            console.log('unbinded');
        }
        count++;
    });
    

    Here is a fiddle

提交回复
热议问题