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

前端 未结 16 1795
面向向阳花
面向向阳花 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 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.

提交回复
热议问题