8

所以我一直在为使用 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 选择器也返回相同的问题)。

4

3 回答 3

2

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

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

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

于 2013-07-25T09:32:47.053 回答
1

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

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

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

// select the target node
var target = document.querySelector('#some-id');
于 2019-02-06T19:50:09.037 回答
0

简单的 MutationObserver:

<div contentEditable id="myID">EDIT TO FIRE</div>
<script>
let x = new MutationObserver(   function(){ alert('FIRED'); }   );
x.observe(  myID , {subtree:true, characterData:true}  );
</script>

看直播:https ://jsfiddle.net/bg8k0jmy/

于 2020-07-20T14:28:21.513 回答