2014-12-23 50 views
0

我一直在遭受一個荒謬的問題。我需要寫我需要編寫window.onload = function()才能使用Javascript

window.onload=function(){ 
//Javascript Code 
} 

使JavaScript工作。

比如我下面的代碼無法正常工作:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

    <head> 
     <title>JS test</title> 
     <script type="text/javascript"> 
     var hours; 
     var minutes; 
     var seconds; 
     var temp; 

     function countdown() { 
     seconds = document.getElementById('countdown').innerHTML; 
     splitt = seconds.split(":"); 
     hours = parseInt(splitt[0], 10); 
     minutes = parseInt(splitt[1], 10); 
     seconds = parseInt(splitt[2], 10); 

     if (hours == 0 && minutes == 0 && seconds == 0) { 
     temp = document.getElementById('countdown'); 
     temp.innerHTML = "all done, bye bye"; 
     return; 
     } 

     if (minutes == 0 && seconds == 0) { 
     hours--; 
     minutes=60; 
     } 
     if (seconds == 0) { 
     minutes--; 
     seconds=60; 
     } 
     seconds--; 
     temp = document.getElementById('countdown'); 
     temp.innerHTML = hours+":"+minutes+":"+seconds; 
     timeoutMyOswego = setTimeout(countdown, 1000); 
     } 

     countdown(); 
     </script></head> 

    <body> 

     <div id="countdown"> 
     47:3:24 
     </div> 

    </body> 
</html> 

但這一個作用:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

    <head> 
     <title>JS test</title> 
     <script type="text/javascript"> 

window.onload=function(){ 
var hours; 
     var minutes; 
     var seconds; 
     var temp; 

     function countdown() { 
     seconds = document.getElementById('countdown').innerHTML; 
     splitt = seconds.split(":"); 
     hours = parseInt(splitt[0], 10); 
     minutes = parseInt(splitt[1], 10); 
     seconds = parseInt(splitt[2], 10); 

     if (hours == 0 && minutes == 0 && seconds == 0) { 
     temp = document.getElementById('countdown'); 
     temp.innerHTML = "all done, bye bye"; 
     return; 
     } 

     if (minutes == 0 && seconds == 0) { 
     hours--; 
     minutes=60; 
     } 
     if (seconds == 0) { 
     minutes--; 
     seconds=60; 
     } 
     seconds--; 
     temp = document.getElementById('countdown'); 
     temp.innerHTML = hours+":"+minutes+":"+seconds; 
     timeoutMyOswego = setTimeout(countdown, 1000); 
     } 

     countdown(); 
} 


     </script></head> 

    <body> 

     <div id="countdown"> 
     47:3:24 
     </div> 

    </body> 
</html> 

我無法弄清楚爲什麼會這樣發生的,爲什麼我需要編寫window.onload = function()爲我的javascript每次工作?

ThankYou。

回答

4
seconds = document.getElementById('countdown') 

在將元素放入DOM之前,您無法從DOM獲取元素。

該腳本在主體加載之前運行。

沒有任何內容添加到DOM中的腳本。

文檔加載完成後運行腳本可避免該問題。

相關問題