对 MutationObserver 感到困惑 [英] Confused About MutationObserver

查看:44
本文介绍了对 MutationObserver 感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在思考如何使用 MutationObserver,但我没有取得任何进展.我已经在 W3C 站点和 MDN 上阅读过它.在 MDN 中阅读时,在示例之前一切都有意义.

So I have been rattling my brain about using the MutationObserver and I haven't made any progress. I've read about it on the W3C site and in the MDN. When reading it in the MDN, everything made sense until the example.

// 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();

我最麻烦的部分是创建观察者实例,不确定那里的语法.同样在控制台中,我收到了类型错误:值没有实现接口节点".无论我看过并尝试使用过哪些示例;将示例中的选择器替换为所需的 jQuery 选择器(非 jQ 选择器也返回相同的问题).

The part I'm having the most trouble with is creating the observer instance, not sure the syntax of what belongs there. Also in the console I've been getting a "TypeError: Value does not implement interface Node." No matter which examples I've looked at and tried using; replacing the selectors in the example with the desired jQuery selectors (also non-jQ selectors returned the same problem).

推荐答案

首先你绝对不应该使用 jQ 选择器,因为它们不是 Node 元素.其次,您必须确保查询选择器不返回空值.为了确保第一次在 document.body 上尝试观察者:它绝对是一个 Node 对象.类似的东西

first you definitely should not use jQ selectors as they are not Node elements. second, you must be sure that query selector returns not null. To make sure try for the first time observer on document.body: it is definitely a Node object. Something like

(
    new MutationObserver(function(mutationEventList){
        console.log(mutationEventList)
    })
)
.observe(document.body, {
    childList: true,
    attributes: true,
    characterData: true
})

当您熟悉以观察者为目标并理解 MutationObserverInit 选项值(它们被描述得不太好)时,您将能够正确地使用mutationObserver.

When you will get familiar with targeting an observer and understand MutationObserverInit options values(they are described not as good as it could) you will be able to work with mutationObserver right.

这篇关于对 MutationObserver 感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆