[英]Why can't observe document.write on document.body using MutationObserver API?
[英]javascript document.body undefined if not preceded by a document.write
有了這個最小的網頁:
<html>
<head>
<title>test</title>
<script type='text/javascript' src='test.js'></script>
</head>
<body>
</body>
</html>
這個最小的“ test.js”腳本失敗:
document.body.innerText = 'testje';
document.body似乎未定義:
0x800a138f - JavaScript runtime error: Unable to set property 'innerText'
of undefined or null reference
如果在代碼行之前添加document.write('blabla'),它將起作用:
document.write('blabla');
document.body.innerText = 'testje';
這使我感到困惑,盡管它看起來很基礎。
我是Javascript新手,所以歡迎您提供一些解釋。
在腳本運行時,沒有body標簽,它還沒有輸出到DOM。
<html>
<head>
<title>test</title>
</head>
<body>
<!-- Place content here -->
<script type='text/javascript' src='test.js'></script>
</body>
</html>
使用document.write
,將使用新內容同步更新document.write
,瀏覽器會修復您的錯誤並添加一個body元素,這就是為什么在document.write
之后可以使用它的原因。
腳本出現在head
。 在運行時,沒有遇到body
的開始,因此body
不存在,無法通過DOM訪問。
document.write
將HTML寫入文檔。 在這種情況下,正在寫入字符數據。 由於字符數據不在允許的head
和用於結束標記head
和用於開始標記body
是可選的,這結束head
元件,並啟動body
。 此時,該body
存在並且可以訪問。
在聲明body元素並且腳本在<head>
運行之前,您無法訪問它。
試試這個: window.onload = function(){ document.body.innerText = 'testje'; };
window.onload = function(){ document.body.innerText = 'testje'; };
或將您的腳本放在<body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.