变异观察者没有检测到文本变化

GTS*_*Joe 11 html javascript jquery mutation-observers

我为什么MutationObserver没有检测到使用textContent完成的文本更改而感到头疼.

HTML

<div id="mainContainer">
  <h1>Heading</h1>
  <p>Paragraph.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

function mutate(mutations) {
  mutations.forEach(function(mutation) {
    alert(mutation.type);
  });
}

jQuery(document).ready(function() {
  setTimeout(function() {
    document.querySelector('div#mainContainer > p').textContent = 'Some other text.';
  }, 2000);

  var target = document.querySelector('div#mainContainer > p')
  var observer = new MutationObserver( mutate );
  var config = { characterData: true, attributes: false, childList: false, subtree: true };

  observer.observe(target, config);
});
Run Code Online (Sandbox Code Playgroud)

在上面的脚本中,段落元素的文本内容明显改变,但MutationObserver没有检测到它.

但是,如果将textContent更改为innerHTML,则会提示您"characterData"已更改.

为什么MutationObserver检测innerHTML但不检测textContent?

这是JS小提琴:

https://jsfiddle.net/0vp8t8x7/

请注意,如果将textContent更改为innerHTML,则只会收到警报.

Ori*_*ori 17

这是因为textContent触发不同的变化innerHTML,你的观察配置未配置为观察所作出的改变textContent.

textContent更改目标的子文本节点.根据MDN设置textContent:

在节点上设置此属性将删除其所有子节点,并将其替换为具有给定值的单个文本节点.

虽然innerHTML改变了元素本身,但它是子树.

所以抓住innerHTML你的配置应该是:

var config = { characterData: true, attributes: false, childList: false, subtree: true };
Run Code Online (Sandbox Code Playgroud)

虽然要抓住textContent使用:

var config = { characterData: false, attributes: false, childList: true, subtree: false };
Run Code Online (Sandbox Code Playgroud)

演示:

function mutate(mutations) {
  mutations.forEach(function(mutation) {
    alert(mutation.type);
  });
}

  setTimeout(function() {
    document.querySelector('div#mainContainer > p').textContent = 'some other text.';
  }, 1000);
  
  var target = document.querySelector('div#mainContainer > p')
  var observer = new MutationObserver( mutate );
  var config = { characterData: false, attributes: false, childList: true, subtree: false };

  observer.observe(target, config);
Run Code Online (Sandbox Code Playgroud)
<div id="mainContainer">
  <h1>Heading</h1>
  <p>Paragraph.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我假设使用 textContent 更改文本不会触发突变观察者回调,但在 Firefox 中它会触发观察者回调,而在 chrome 上则不会。您能分享一下为什么会发生这种情况吗? (3认同)