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

前端 未结 16 1786
面向向阳花
面向向阳花 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') { ... }

    0 讨论(0)
  • 2020-11-22 17:58

    I like mtkopone's answer using jQuery special events, but note that it doesn't work a) when elements are detached instead of removed or b) when some old non-jquery libraries use innerHTML to destroy your elements

    0 讨论(0)
  • 2020-11-22 18:01

    The "remove" event from jQuery works fine, without addition. It might be more reliable in time to use a simple trick, instead of patching jQuery.

    Just modify or add an attribute in the element you are about to remove from the DOM. Thus, you can trigger any update function, that will just ignore elements on way to be destroyed, with the attribute "do_not_count_it".

    Suppose we have a table with cells corresponding to prices, and that you need to show only the last price: This is the selector to trigger when a price cell is deleted (we have a button in each line of the table doing that, not shown here)

    $('td[validity="count_it"]').on("remove", function () {
        $(this).attr("validity","do_not_count_it");
        update_prices();
    });
    

    And here is a function that finds the last price in the table, not taking account of the last one, if it was the one that was removed. Indeed, when the "remove" event is triggered, and when this function is called, the element is not removed yet.

    function update_prices(){
          var mytable=$("#pricestable");
          var lastpricecell = mytable.find('td[validity="count_it"]').last();
    }
    

    In the end, the update_prices() function works fine, and after that, the DOM element is removed.

    0 讨论(0)
  • 2020-11-22 18:01

    referencing to @David answer:

    When You want to do soo with another function, eg. html() like in my case, don't forget to add return in new function:

    (function() {
        var ev = new $.Event('html'),
            orig = $.fn.html;
        $.fn.html = function() {
            $(this).trigger(ev);
            return orig.apply(this, arguments);
        }
    })();
    
    0 讨论(0)
提交回复
热议问题