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

前端 未结 16 1951
面向向阳花
面向向阳花 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:58

    You can use jQuery special events for this.

    In all simplicity,

    Setup:

    (function($){
      $.event.special.destroyed = {
        remove: function(o) {
          if (o.handler) {
            o.handler()
          }
        }
      }
    })(jQuery)
    

    Usage:

    $('.thing').bind('destroyed', function() {
      // do stuff
    })
    

    Addendum to answer Pierre and DesignerGuy's comments:

    To not have the callback fire when calling $('.thing').off('destroyed'), change the if condition to: if (o.handler && o.type !== 'destroyed') { ... }

提交回复
热议问题