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

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

    Hooking .remove() is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html(), .replace(), etc).

    In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData() for each removed element regardless of the method used to remove it.

    See this answer for more details: javascript memory leaks

    So, for best results, you should hook the cleanData function, which is exactly what the jquery.event.destroyed plugin does:

    http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js

提交回复
热议问题