【发布时间】:2021-12-24 19:30:18
【问题描述】:
我已尝试使用 DOMSubtreeModified,但跨度有一个数据,每次更改时都会向我抛出事件。如何仅将文本更改与垃圾邮件隔离开来?
【问题讨论】:
我已尝试使用 DOMSubtreeModified,但跨度有一个数据,每次更改时都会向我抛出事件。如何仅将文本更改与垃圾邮件隔离开来?
【问题讨论】:
我推荐使用MutationObserver 接口,它提供了监视对DOM 树所做的更改的能力。它旨在替代旧的 Mutation Events 功能,该功能是 DOM3 事件规范的一部分。
MutationObserver 创建并返回一个新的 MutationObserver,它将在 DOM 发生更改时调用指定的回调函数,因此在回调中您可以实际检查更改的突变的类型。
// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type); // will log the type that was changed
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
更多关于MutationObserver - https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
【讨论】: