![](/img/trans.png)
[英]parentNode is null with MutationObserver.observe(document.body
[英]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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.