困惑关于MutationObserver

问题描述 投票:6回答:2

所以我一直在喋喋不休地谈论使用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:Value没有实现接口Node”。无论我看过哪些例子并尝试使用过;用所需的jQuery选择器替换示例中的选择器(非jQ选择器也返回了同样的问题)。

javascript syntax mutation-observers
2个回答
0
投票

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

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

当您熟悉定位观察者并了解MutationObserverInit选项值(它们的描述不尽如人意)时,您将能够正确使用mutationObserver。


0
投票

MutationObserver是一个非常强大的功能,它允许您监视DOM中节点/对象的所有类型的更改。在他们的例子中,他们在这里创建观察者:

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });   
});

并在这里称呼它:

// pass in the target node, as well as the observer options
observer.observe(target, config);

目标是一个节点,配置告诉它在该节点上监视什么。您可以监视各种事物,在他们的示例中,它们监视属性,childList和characterData发生更改的时间。如果由于javascript操作或用户操作而导致任何这些项目发生更改,则观察者将触发并向您提供有关更改内容的信息,并允许您根据更改类型采取操作。最容易看到它发生在控制台中。

要进行测试,请确保选择了有效目标:

// select the target node
var target = document.querySelector('#some-id');
© www.soinside.com 2019 - 2024. All rights reserved.