简体   繁体   English

Mutation Observer无法检测元素的dom移除

[英]Mutation Observer fails to detect element's dom removal

So, I thought this was going to be pretty straight forward, there used to be a DOMNodeRemoved event, but that's deprecated, instead, MutationObserver should be used, the thing is, it doesn't fire, even whith the appropiate configuration. 所以,我认为这将是非常简单的,曾经是一个DOMNodeRemoved事件,但是已经弃用了,相反,应该使用MutationObserver ,事实是,它不会触发,即使是合适的配置。

According to this article about migrating from mutating events to mutation observers the configuration to detect dom removal of a node is { childList: true, subtree: true } , and that fits giving that childList is obligatory and subtree means it will capture mutations to not just target, but also target's descendants are to be observed according to the mdn article . 根据这篇关于从变异事件迁移到变异观察者的文章,用于检测节点的dom移除的配置是{ childList: true, subtree: true } ,并且适合给出childList是必须的,而subtree意味着它将捕获突变而不仅仅是目标,但也根据mdn文章 观察目标的后代

Anyway, I've made a jsfiddle of the problem, it's pretty straight forward, the <button> removes the <div> and the observer should log the mutation records, but it doesn't, see if you can figure it out :) 无论如何,我做了一个的jsfiddle的问题,这是很简单的,在<button>删除<div>和观测记录这一突变的记录,但它并没有,看看你是否可以计算出来:)

HTML HTML

<div>Oh my god karen, you can't just ask someone why they're white.</div>
<button>^Remove</button>

JavaScript JavaScript的

div = document.querySelector("div");
callback = function(records){
    console.log(records);
}
config = {
    childList:true,
    subtree:true
}
observer = new MutationObserver(callback);
observer.observe(div,config);

button = document.querySelector("button");
button.addEventListener("click",function(){
    div.parentNode.removeChild(div);
});

Thanks! 谢谢!

As the names suggest childList only captures changes to list of immediate children of an observed node and subtree extends any specified criteria to all descendants (it doesn't do anything on its own). 正如名称所示, childList仅捕获对观察节点的直接子节点列表的更改,并且subtree将任何指定的条件扩展到所有后代(它本身不做任何事情)。

But you are doing neither. 但你两个都没做。 You are removing the observed node itself while leaving its descendants unchanged. 您正在删除观察到的节点本身,同时保持其后代不变。

Simply observing div.parentNode instead should solve your problem. 只需观察div.parentNode解决您的问题。

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

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