繁体   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