[英]Confused About MutationObserver
所以我一直在思考使用 MutationObserver 的問題,但我沒有取得任何進展。 我已經在 W3C 站點和 MDN 上閱讀過它。 在 MDN 中閱讀時,在示例之前一切都有意義。
// 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();
我最麻煩的部分是創建觀察者實例,不確定那里的語法。 同樣在控制台中,我收到了“類型錯誤:值沒有實現接口節點”。 無論我看過並嘗試使用過哪些示例; 用所需的 jQuery 選擇器替換示例中的選擇器(非 jQ 選擇器也返回相同的問題)。
首先你絕對不應該使用 jQ 選擇器,因為它們不是 Node 元素。 其次,您必須確保查詢選擇器不返回空值。 為了確保第一次在 document.body 上嘗試觀察者:它絕對是一個 Node 對象。 就像是
(
new MutationObserver(function(mutationEventList){
console.log(mutationEventList)
})
)
.observe(document.body, {
childList: true,
attributes: true,
characterData: true
})
當您熟悉以觀察者為目標並理解 MutationObserverInit 選項值(它們被描述得不是那么好)時,您將能夠正確地使用mutationObserver。
MutationObserver 是一項非常強大的功能,可讓您監控 DOM 中節點/對象上的所有類型的更改。 在他們的例子中,他們在這里創建了觀察者:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
並在這里調用它:
// pass in the target node, as well as the observer options
observer.observe(target, config);
目標是一個節點,配置告訴它在該節點上監視什么。 您可以監視各種事物,在他們的示例中,它們正在監視屬性、 childList和characterData何時發生更改。 如果這些項目中的任何一個由於 javascript 操作或用戶操作而發生變化,觀察者將觸發並為您提供有關更改內容的信息,並讓您根據更改的類型采取行動。 在控制台中最容易看到它發生。
要進行測試,請確保您選擇了一個有效的目標:
// select the target node
var target = document.querySelector('#some-id');
簡單的 MutationObserver:
<div contentEditable id="myID">EDIT TO FIRE</div>
<script>
let x = new MutationObserver( function(){ alert('FIRED'); } );
x.observe( myID , {subtree:true, characterData:true} );
</script>
見直播: https : //jsfiddle.net/bg8k0jmy/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.