删除元素时的DOM事件 [英] DOM event when element is removed
问题描述
当从DOM中删除元素时,有没有办法获得通知,直接或作为子树的一部分?似乎唯一可用的方法仅适用于直接删除的节点,但我希望在包含我的节点的整个子树被删除时收到通知。
Is there any way to get notification when an element is removed from the DOM, either directly or as part of a subtree? It seems like the only methods available are just for directly removed nodes, but I would like to get a notification when a whole subtree that contains my node is removed.
编辑
似乎问题并不完全清楚,所以我提出了挑战: https://jsbin.com/winukaf
Seems the problem wasn't entirely clear, so I have made a challenge: https://jsbin.com/winukaf
DOM看起来像这样:
The DOM looks like this:
<body>
<div class="root">
<div class="great-grand-parent">
<div class="grand-parent">
<div class="parent">
<div class="leaf">
Am I still here?
</div>
</div>
</div>
</div>
</div>
</body>
并且挑战是在删除此处的任何一个元素时通知,因为这将删除来自DOM树的叶节点。
and the challenge is to notify when any one of the elements here are removed, since that will remove the leaf node from the DOM tree.
推荐答案
有一个名为 MutationObserver 它有相当不错的支持
There's a HTML5 API called MutationObserver and it has pretty good support
以下是一个例子:
// Element is the whatever subtree/element you need to watch over
var in_dom = document.body.contains(element);
var observer = new MutationObserver(function(mutations) {
if (document.body.contains(element)) {
if (!in_dom) {
console.log("element inserted");
}
in_dom = true;
} else if (in_dom) {
in_dom = false;
console.log("element removed");
}
});
observer.observe(document.body, {childList: true, subtree: true});
这篇关于删除元素时的DOM事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!