Mutation Observer 未能检测到元素的 dom 移除

Mutation Observer fails to detect element's dom removal

所以,我认为这会非常简单,曾经有一个 DOMNodeRemoved 事件,但它已被弃用,相反,应该使用 MutationObserver,事实是,它即使配置适当,也不会触发。

根据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.

无论如何,我已经对问题做了 jsfiddle,它非常简单,<button> 删除了 <div> 并且观察者应该记录突变记录,但是它不会,看看你能不能想出来:)

HTML

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

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);
});

谢谢!

顾名思义,childList 仅捕获对观察到的节点的直接子节点列表的更改,subtree 将任何指定的条件扩展到所有后代(它自己不做任何事情) .

但你两者都不做。您正在删除观察到的节点本身,同时保留其后代不变。

只需观察 div.parentNode 即可解决您的问题。