簡體   English   中英

如何檢測從 dom 元素中添加/刪除的元素?

[英]How to detect element being added/removed from dom element?

假設我有一個div#parent和我append並使用 jquery remove它的元素。我如何才能檢測到div#parent元素上何時發生這樣的事件?

不要使用像 DOMNodeInserted 和 DOMNodeRemoved 這樣的突變事件。

相反,使用 DOM Mutation Observers ,它在除 IE10 及更低版本(我可以使用)之外的所有現代瀏覽器中都受支持。 突變觀察者旨在取代突變事件(已被棄用),因為它們被發現由於其設計缺陷而性能低下。

var x = new MutationObserver(function (e) {
  if (e[0].removedNodes) console.log(1);
});

x.observe(document.getElementById('parent'), { childList: true });

按照@Qantas 在他的回答中的建議使用Mutation Observers


以下方法已棄用

您可以使用DOMNodeInsertedDOMNodeRemoved

$("#parent").on('DOMNodeInserted', function(e) {
    console.log(e.target, ' was inserted');
});

$("#parent").on('DOMNodeRemoved', function(e) {
    console.log(e.target, ' was removed');
});

MDN 文檔

你應該綁定DOMSubtreeModified事件

$("#parent").bind("DOMSubtreeModified",function(){
  console.log('changed');
});

http://jsfiddle.net/WQeM3/

它不會讓我在下面對最佳答案發表評論,而是回答你的問題@DenisKolodin,為了傾聽自我毀滅,你可以這樣做:

function watchElForDeletion(elToWatch, callback, parent = document.querySelector('body')){
  const observer = new MutationObserver(function (mutations) {

    // loop through all mutations
    mutations.forEach(function (mutation) {

        // check for changes to the child list
        if (mutation.type === 'childList') {

            // check if anything was removed and if the specific element we were looking for was removed
            if (mutation.removedNodes.length > 0 && mutation.removedNodes[0] === elToWatch) {
                callback();
            }
        }
    });
  });

  // start observing the parent - defaults to document body
  observer.observe(parent, { childList: true });
};

它默認父元素是正文元素,並且僅在您要查找的特定元素被刪除時才運行回調。

我想我們使用 socket.io..

因為我們檢測應該添加哪個元素然后可能猜測哪個元素將被刪除

也許有可能

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM