所以我一直在绞尽脑汁地思考如何使用MutationObserver,但没有取得任何进展。我在 W3C 网站和 MDN 上读到过相关内容。当在 MDN 中阅读它时,在示例之前一切都有意义。
// 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);
});
});
// 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();
我遇到的最麻烦的部分是创建观察者实例,不确定属于那里的语法。另外,在控制台中,我收到“TypeError:值未实现接口 Node”。
无论我看过并尝试使用哪些示例;将示例中的选择器替换为所需的 jQuery 选择器(非 jQ 选择器也返回相同的问题)。
首先,你绝对不应该使用 jQ 选择器,因为它们不是 Node 元素。
其次,您必须确保查询选择器返回不为空。
为了确保第一次尝试观察 document.body:它绝对是一个 Node 对象。
就像是
(
new MutationObserver(function(mutationEventList){
console.log(mutationEventList)
})
)
.observe(document.body, {
childList: true,
attributes: true,
characterData: true
})
当您熟悉以观察者为目标并了解 MutationObserverInit 选项值(它们的描述并不那么好)时,您将能够正确使用 MutationObserver。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)