2013-05-18 251 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工作權。