为什么MutationObserver代码不能在Chrome 30上运行? [英] Why doesn't MutationObserver code run on Chrome 30?

查看:603
本文介绍了为什么MutationObserver代码不能在Chrome 30上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers I got the following code:

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

jsFiddle: http://jsfiddle.net/cUNH9

jsFiddle: http://jsfiddle.net/cUNH9

如您所见,我们应该看到一个警告,因为 div 元素被插入到DOM中。但看起来MutationObserver代码不会运行。如何成功运行MutationObserver代码?

As you can see , we should see a alert because a div element is inserted to the DOM. But it appears MutationObserver codes don't run. How can I successfully make the MutationObserver code run?

推荐答案

添加 subTree 选项,它应该工作,你不仅要监视文档的子项( head / body ),但它也是后代。 (这就是设置为 document.body 的原因)。

Add subTree option as well, it should work, you want to monitor not just children of document ( head/body) but it's descendants as well. (And that is the reason when set to document.body it works).

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

小提琴

Fiddle

来自文档


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

subtree: Set to true if mutations to not just target, but also target's descendants are to be observed.

所以你要添加的是文件的后代而不是它的孩子(或直系后代)。它是 body 的孩子(这就是为什么只提到 childList 并使用文档。正文有效)。如果你想深入监控变化,你需要提及 subTree

So what you are adding is a descendant of the document not its child (or direct descendant). It is a child of body (and that is why just mentioning childList and using document.body works). You need to mention subTree if you want to monitor the changes deep.

另请参阅说明:


注意:至少,childList,attributes或characterData必须设置为true。否则,抛出指定了无效或非法字符串错误。

NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.

这篇关于为什么MutationObserver代码不能在Chrome 30上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆