如何检测正在从dom元素中添加/删除的元素

How to detect element being added/removed from dom element?

本文关键字:元素 dom 添加 删除 何检测 检测      更新时间:2023-09-26

假设我使用jquery有一个div#parentappendremove元素。当div#parent元素上发生此类事件时,我将如何检测?

不要使用DOMNodeInserted和DOMNodeRemoved等突变事件

相反,使用DOM突变观测器,除IE10及更低版本外,所有现代浏览器都支持它(我可以使用吗)。突变观测器旨在取代突变事件(已被弃用),因为由于其设计缺陷,它们的性能较低。

var x = new MutationObserver(function (e) {
  if (e[0].removedNodes) console.log(1);
});
x.observe(document.getElementById('parent'), { childList: true });

按照@Qantas在其回答中的建议使用突变观测器


下列方法已弃用

您可以使用DOMNodeInserted和DOMNodeRemoved

$("#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 });
};

它默认将父元素作为body元素,并且只有在您要查找的特定元素被删除时才运行回调。

我认为我们使用socket.io!。

因为我们检测应该添加哪个元素,然后可能猜测哪个元素将被删除

也许是可能的

感谢