2013-02-19 40 views
0
<!DOCTYPE HTML> 
<html> 
<head> 
<script> 
document.write("TEST1") 
document.getElementById("demo").innerHTML="TEST2" 
document.write("TEST3") 
</script> 
</head> 

<body> 
<p id="demo">TO_BE_REPLACED</p> 
</body> 
</html> 

這裏是輸出: TEST1javascript - 爲什麼不用innerHTML替換運行?

TO_BE_REPLACED 

似乎執行已停在document.getElementById("demo").innerHTML="TEST2"的JavaScript。爲什麼不執行?

+3

看到這個:http://stackoverflow.com/questions/5704924/executing-javascript-in-the-head-getelementbyid-returns-null,http://stackoverflow.com/questions/8864776/getelementbyid -and-null-why,http://stackoverflow.com/questions/5371047/getelementbyid-returns-null-even-though-the-element-exists或http://stackoverflow.com/questions/10839271/null-return -by-getelementbyid-method-in-javascript – HoLyVieR 2013-02-19 02:45:21

回答

3

當腳本正在運行時,<p id="demo">尚不存在。因此,document.getElementById('demo')正在恢復null,當你嘗試分配null.innerHTML = "TEST2"

此錯誤停止所有執行,然後觸發一個錯誤,所以你從來沒有看到最終的TEST3

+0

感謝您的幫助! – CDT 2013-02-19 02:58:47

1

您需要附上腳本的,將在窗口的負載(用「的window.onload」事件)被調用的函數。

<!DOCTYPE HTML> 
<html> 
<head> 
<script> 
    function replaceDemoText() 
    { 
     document.getElementById("demo").innerHTML="TEST2"; 
    } 
    window.onload = replaceDemoText; 
</script> 
</head> 

<body> 
<p id="demo">TO_BE_REPLACED</p> 
</body> 
</html> 
+0

謝謝,它的作品〜! – CDT 2013-02-19 03:08:24