2013-05-18 250 views
5

所以我一直在使用MutationObserver敲打我的大脑,我还没有取得任何进展。我在W3C网站和MDN上阅读过它。在MDN中阅读时,一切都有意义,直到示例。关于MutationObserver的困惑

// select the target node 
var target = document.querySelector('#some-id'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    console.log(mutation.type); 
    }); 
}); 

// configuration of the observer: 
var config = { attributes: true, childList: true, characterData: true }; 

// pass in the target node, as well as the observer options 
observer.observe(target, config); 

// later, you can stop observing 
observer.disconnect(); 

我最麻烦的部分是创建观察者实例,不确定那里属于哪里的语法。另外在控制台中,我得到了一个“TypeError:Value没有实现接口节点”。 无论我看过并尝试使用哪些示例,用所需的jQuery选择器替换示例中的选择器(也是非jQ选择器返回相同的问题)。

+0

MutationObserver与jQuery不相关。查询选择器可能看起来很像嘶嘶声,但它们不共享一个实现。 – Halcyon

+0

你有一个id为“some-id”的元素吗? – bfavaretto

+0

@Frits van Campen我知道他们没有关系,我使用jQ库,不过,无论我是否使用jQ选择器,我都会收到TypeError消息。 –

回答

0

首先你绝对不应该使用jQ选择器,因为它们不是Node元素。 秒,你必须确保查询选择器返回非空。 要确保在document.body上第一次观察者尝试:它肯定是一个Node对象。 喜欢的东西

(
    new MutationObserver(function(mutationEventList){ 
     console.log(mutationEventList) 
    }) 
) 
.observe(document.body, { 
    childList: true, 
    attributes: true, 
    characterData: true 
}) 

当你将熟悉目标的观察员,了解MutationObserverInit选项的值(它们被描述没有那么好,因为它可以),你将能够与mutationObserver工作权。