单个 MutationObserver 对象可以观察多个目标吗?

Can a single MutationObserver object observe multiple targets?

我想使用 MutationObserver 对象来观察我的某些 DOM 节点的变化。

文档给出了创建 MutationObserver 对象并将其注册到目标的示例。

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

假设我有上面的代码,但就在它下面,我放置了这段代码:

var target2 = document.querySelector('#some-other-id');
var config2 = {attributes: true, subtree: true};
observer.observe(target2, config2);

observer:

观察者现在将观察两个目标 - 根据您的定义 targettarget2。不会抛出任何错误,并且 target 不会 "unregistered" 支持 target2。不会出现意外或其他行为。

这里是一个在两个 contenteditable 元素上使用相同 MutationObserver 的示例。要查看此内容,请从每个 contenteditable 元素中删除 <span> 节点并查看两个观察到的元素的行为跨度。

<div id="myTextArea" contenteditable="true">
    <span contenteditable="false">Span A</span>
</div>

<div id="myTextArea2" contenteditable="true">
    <span contenteditable="false">Span B</span>
</div>

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
      //console.log($(mutation.removedNodes)); // <<-- includes text nodes

      $(mutation.removedNodes).each(function(value, index) {
          if(this.nodeType === 1) {
              console.log(this)
          }
      });
  });
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe($('#myTextArea')[0], config);

observer.observe($('#myTextArea2')[0], config);

JSFiddle Link - 演示

请注意,我已经为第一个演示回收了相同的配置,但是,放置一个新配置将专用于该观察到的元素。以 config2 中定义的示例为例,如果在 #myTextArea2 上使用,您将不会根据配置选项看到记录的节点,但请注意 #myTextArea 的观察者不受影响。

JSFiddle Link - 演示 - 配置排他性