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(使用前将#替换为@)