简体   繁体   English

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

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

Say I had a div#parent and I append and remove elements to it using jquery. How would I be able to detect when such an event happens on the div#parent element?假设我有一个div#parent和我append并使用 jquery remove它的元素。我如何才能检测到div#parent元素上何时发生这样的事件?

Don't use mutation events like DOMNodeInserted and DOMNodeRemoved.不要使用像 DOMNodeInserted 和 DOMNodeRemoved 这样的突变事件。

Instead, use DOM Mutation Observers , which are supported in all modern browsers except IE10 and lower ( Can I use ).相反,使用 DOM Mutation Observers ,它在除 IE10 及更低版本(我可以使用)之外的所有现代浏览器中都受支持。 Mutation observers are intended to replace mutation events (which have been deprecated), as they have been found to have low performance due to flaws in its design .突变观察者旨在取代突变事件(已被弃用),因为它们被发现由于其设计缺陷而性能低下。

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

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

Use Mutation Observers as suggested by @Qantas in his answer按照@Qantas 在他的回答中的建议使用Mutation Observers


Following methods are deprecated以下方法已弃用

You can use DOMNodeInserted and DOMNodeRemoved您可以使用DOMNodeInsertedDOMNodeRemoved

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

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

MDN Docs MDN 文档

You should bind DOMSubtreeModified event你应该绑定DOMSubtreeModified事件

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

http://jsfiddle.net/WQeM3/ http://jsfiddle.net/WQeM3/

It wouldn't let me comment below on the top answer but to answer your question @DenisKolodin, in order to listen for self-destruction, you can do something like this:它不会让我在下面对最佳答案发表评论,而是回答你的问题@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 });
};

It defaults to the parent being the body element and only runs the callback if the specific element you're looking for is deleted.它默认父元素是正文元素,并且仅在您要查找的特定元素被删除时才运行回调。

I think we use socket.io..我想我们使用 socket.io..

because of we detect which element should be added and then possibly to guess which element will be removed因为我们检测应该添加哪个元素然后可能猜测哪个元素将被删除

Maybe it's possible也许有可能

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM