为什么 MutationObserver 代码不能在 Chrome 30 上运行?

2024-01-06

From http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers我得到以下代码:

var insertedNodes = [];
var observer = new WebKitMutationObserver(function(mutations) {
 alert('run');
 mutations.forEach(function(mutation) {
   for (var i = 0; i < mutation.addedNodes.length; i++)
     insertedNodes.push(mutation.addedNodes[i]);
 })
});
observer.observe(document, { childList: true });
console.log(insertedNodes);

var divElement = document.createElement('div');
divElement.innerHTML = 'div element';
document.querySelector('body').appendChild(divElement);

js小提琴:http://jsfiddle.net/cUNH9 http://jsfiddle.net/cUNH9

正如您所看到的,我们应该看到一条警报,因为div元素被插入到 DOM 中。但 MutationObserver 代码似乎无法运行。如何成功运行 MutationObserver 代码?


Add subTree选项也是如此,它应该可以工作,您想要监控的不仅仅是文档的子级(head/body)但它也是后代。 (这就是设置为document.body有用)。

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

Fiddle http://jsfiddle.net/mqLkk/

From 文档 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

子树:如果不仅要观察目标的突变,还要观察目标后代的突变,则设置为 true。

所以你要添加的是document不是它的孩子(或直系后代)。它是一个孩子body(这就是为什么只提到childList并使用document.body作品)。你需要提及subTree如果你想深入监控变化。

另请参阅注释:

注意:至少,childList、attributes 或characterData 必须设置为true。否则,将引发“指定了无效或非法字符串”错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 MutationObserver 代码不能在 Chrome 30 上运行? 的相关文章

随机推荐