【问题标题】:MutationObserver not working突变观察者不工作
【发布时间】:2015-09-05 22:47:16
【问题描述】:

考虑以下代码:

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.target.nodeName);
  });
});

observer.observe(document, {
  attributes: true,
  childList: true,
  characterData: true
});
<div>
  <ol contenteditable oninput="">
    <li>Press enter</li>
  </ol>
</div>

这是对this 的轻微修改。

jsbin version 页面交互不会产生任何日志。我哪里错了?请注意,如果我替换行

  observer.observe(document, {

  observer.observe(document.querySelector('ol'), {

脚本开始工作...

【问题讨论】:

  • observer.observe(list, ...) 如何工作?没有这样的变量。
  • 对不起,我已经更正了脚本。 list 出现引用了引用的原始脚本。

标签: javascript mutation-observers


【解决方案1】:

它似乎不起作用,因为你没有改变你正在观察的任何东西。你没有改变

  • document 节点的属性(attributes: true)(这是可以理解的,因为document 没有属性)
  • 子节点(childList: true):document 的唯一子节点是&lt;html&gt; 节点,您不会删除或替换它。
  • 字符数据 (characterData: true):您没有更改 document 的任何 Text、Comment 或 ProcessingInstruction 子级(也可以理解,因为 document 不能有这样的子级)。

如果您替换 &lt;html&gt; 节点,您可以看到突变观察者按配置工作。

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.target.nodeName);
  });
});

observer.observe(document, {
  attributes: true,
  childList: true,
  characterData: true
});

document.replaceChild(document.createElement('div'), document.documentElement);

您所做的是更改ol 元素的内容,它是document后代

如果你想听这些变化,你必须将subtree设置为true:

observer.observe(document, {
  attributes: true,
  childList: true,
  subtree: true,
  characterData: true
});

更多信息在MDN documentation

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.target.nodeName);
  });
});

observer.observe(document, {
  attributes: true,
  childList: true,
  subtree: true,
  characterData: true
});
<div>
  <ol contenteditable oninput="">
    <li>Press enter</li>
  </ol>
</div>

【讨论】:

  • 您的characterData: true 描述不太正确。 characterData 适用于直接或通过 subtree: true 观察文本/注释/处理指令时,而不是当这些节点类型是观察元素的子节点时。
  • @loganfsmyth:不确定subtree 如何影响其他设置。感谢您的澄清。
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 2012-05-20
  • 2011-04-14
  • 2013-01-30
  • 2017-12-04
  • 1970-01-01
  • 2018-06-15
  • 2013-12-21
相关资源
最近更新 更多