困惑关于MutationObserver

Kni*_*shi 6 javascript syntax mutation-observers

所以我一直在喋喋不休地谈论使用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();
Run Code Online (Sandbox Code Playgroud)

我最麻烦的部分是创建观察者实例,不确定属于那里的语法.同样在控制台中我得到了一个"TypeError:Value没有实现接口Node".无论我看过哪些例子并尝试使用过; 用所需的jQuery选择器替换示例中的选择器(非jQ选择器也返回了同样的问题).

Jab*_*her 2

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

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

当您熟悉以观察者为目标并了解 MutationObserverInit 选项值(它们的描述并不那么好)时,您将能够正确使用 MutationObserver。