gpt4 book ai didi

Javascript DOM 添加/删除事件

转载 作者:行者123 更新时间:2023-12-01 02:03:53 27 4
gpt4 key购买 nike

我希望在从 DOM 树中删除元素时执行一些清理工作,更具体地说,是 ParentElement.removeChild(ChildElement) 。我想知道当 ChildElement 被删除时是否会发出任何可以在代码中监听的事件?

最佳答案

是的,您可以使用 MutationObserver 监听对 DOM 的操作.

来自 MDN 文档的示例:

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

关于Javascript DOM 添加/删除事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50282798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com