jQuery - DOM から要素が削除されたときにイベントをトリガーする 質問する

jQuery - DOM から要素が削除されたときにイベントをトリガーする 質問する

ページから要素が削除されたときに、いくつかの js コードを実行する方法を理解しようとしています。

jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */

次のような、それに合わせたイベントはありますか?

jQuery('#some-element').onremoval( function() {
    // do post-mortem stuff here
});

ベストアンサー1

これにはjQuery の特別なイベントを使用できます。

シンプルに言えば、

設定:

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

使用法:

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

Pierre と DesignerGuy のコメントに対する補足:

を呼び出すときにコールバックが実行されないようにするには$('.thing').off('destroyed')、if 条件を次のように変更します。if (o.handler && o.type !== 'destroyed') { ... }

おすすめ記事