我在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。