2010-04-13 82 views
15

我一直使用document.GetElementById成功,但從一段時間以來我無法再使它工作。 中,我用它仍然可以工作舊的網頁,但事情像這樣簡單:爲什麼document.GetElementById返回null

<html> 
<head> 
<title>no title</title> 
<script type="text/javascript"> 
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?"; 
</script> 
</head> 
<body> 
<div id="ThisWillBeNull"></div> 
</body> 
</html> 

現在給我「的document.getElementById(」 parsedOutput「)爲空」的所有時間。 如果我使用Firefox或Chrome,或者我啓用了哪些擴展或者我爲html使用了哪些頭文件,它無關緊要,它始終爲空,我無法找到可能出錯的地方。

感謝您的輸入=)

回答

36

頁面呈現從上到下。你的代碼在解析後立即執行。在執行時,div還不存在。你需要把它包裝在一個window.onload函數中。

24

試試這個:

<script type="text/javascript"> 
    window.onload = function() { 
    document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?"; 
    } 
</script> 
1

瀏覽器是要儘快找到它執行該腳本。此時,文檔的其餘部分尚未加載 - 沒有任何元素具有該id。如果你在之後運行代碼那部分文件被加載,它將正常工作。

4

沒有window.onload您的腳本從不被調用。 Javascript是一種基於事件的語言,因此沒有像onload,onclick,onmouseover這樣的顯式事件,腳本不會運行。

<script type="text/javascript"> 
    window.onload = function(){ 
    document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?"; 
    } 
</script> 

onLoad事件:在原稿載置過程結束

負載事件觸發。此時,文檔中的所有對象都在DOM中,並且所有圖像和子幀都已完成加載。

https://developer.mozilla.org/en/DOM/window.onload

1
<script type="text/javascript"> 
    window.onload += function() { 
    document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?"; 
    } 
</script> 

使用+=分配更eventHandler s到爲onload的文檔事件。

+0

這對我沒有任何幫助。 – Mixxiphoid 2015-11-13 19:51:29

相關問題