簡體   English   中英

為什么不能使用MutationObserver API在document.body上觀察document.write?

[英]Why can't observe document.write on document.body using MutationObserver API?

我沒有在document.write上觀察document.body 這是代碼:

<script>
var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
        eventListenerSupported = window.addEventListener;

    return function(obj, callback){
        if( MutationObserver ){
            // define a new observer
            var obs = new MutationObserver(function(mutations, observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                    callback();
            });
            // have the observer observe foo for changes in children
            obs.observe( obj, { childList:true, subtree:true });
        }
        else if( eventListenerSupported ){
            obj.addEventListener('DOMNodeInserted', callback, false);
            obj.addEventListener('DOMNodeRemoved', callback, false);
        }
    }
})();

window.onload = function() {
    //console.log("dom ready");

    // Observe a specific DOM element:
    observeDOM( document.body ,function(){ 
        console.log('dom changed');
    });
}

function reload() {
    document.write("<input type=\"submit\" onclick=\"reload();\" value=\"Reload\" />");

    //var text = document.createTextNode("abc");
    //document.body.appendChild(text);
}
</script>
<body>
<input type="submit" onclick="reload();" value="Reload" />
</body>

當我單擊“ Reload按鈕時,沒有任何記錄。 但是,如果我將window.onload代碼更改為:

observeDOM( document ,function(){ // change first parameter to *document*
    console.log('dom changed');
});

然后單擊“ Reload ,控制台輸出dom changed 誰能說出原因? 我正在使用Chrome v50。

我今天找到了原因。 看來document.write()覆蓋了一個新的document.body 由於MutationObserver被附加到舊的document.body ,它無法在新body上觀察到DOM的變化。

這是我測試它的方式:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM