我需要编写window.onload = function()来使Javascript工作

时间:2014-12-23 10:15:24

标签: javascript function window onload

我一直在遭遇一个荒谬的问题。我需要写

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。

1 个答案:

答案 0 :(得分:4)

seconds = document.getElementById('countdown')

在将元素放入DOM之前,您无法从DOM中获取元素。

脚本在加载正文之前运行。

脚本可以使用添加到正文中DOM的任何内容。

文档加载完成后运行脚本可避免此问题。