如何使用MutationObserver? [英] How to use MutationObserver?

查看:99
本文介绍了如何使用MutationObserver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个令人敬畏的 MutationObserver 功能,它可以跟踪任何dom元素的变化。我使用了mozilla开发人员网络上显示的代码,但似乎无法使其运行。这是我使用的代码(链接):

I recently came across this awesome MutationObserver feature which sort of keep tracks of the changes on any dom element. I used the code that was shown on the mozilla developer network, but can't seem to make it run. This is the code I used (link):

   // create an observer instance
var target = document.querySelector('#something');
console.log(target);
var observer = new WebKitMutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      console.log("Success");
        //$('#log').text('input text changed: "' + target.text() + '"');
        //console.log(mutation, mutation.type);
    });    
});
observer.observe(target, { attributes: true, childList: true, characterData: true });
//observer.disconnect(); - to stop observing

// test case
setInterval(function(){
    document.querySelector('#something').innerHTML = Math.random();
},1000);

以上代码似乎不起作用。但是,如果我用一些jQuery修改相同的代码,一切似乎都可以正常工作(演示这里 )。有没有我在文档中遗漏的东西,或者我只是误解了观察者的特征。

The above code doesn't seems to work. However if I modify the same code with a bit of jQuery, everything seems to work just fine (Demo here). Is there something I'm missing from the docs or I'm just misinterpreting the observer feature.

推荐答案

你需要子树:true

http://jsfiddle.net/6Jajs/1/

内部文本通常是DOM中的子text()元素。没有子树,它只会观察元素本身。

The inner text would normally be a child text() element in the DOM. Without the subtree it will only watch the element itself.

围绕characterData可能存在混淆( https://developer.mozilla.org/en-US/docs/Web/API/CharacterData ),但似乎仅适用于直接包含文本的节点。 DOM的结构使得大多数标记元素包含混合类型,可选择包括子文本节点(后者将实现characterData,但它将是目标节点的子节点)。

There is possible confusion surrounding "characterData" (https://developer.mozilla.org/en-US/docs/Web/API/CharacterData), but it seems that that applies only to nodes that directly contain text. The DOM is structured so that most markup elements contain mixed type which optionally include a child text node (which in turn would implement characterData, but would be a child of the targeted node).

这篇关于如何使用MutationObserver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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