getElementById(...)为null。在Firebug中正常工作

时间:2013-06-03 17:24:56

标签: javascript html

TypeError:document.getElementById(...)为null。 不知道为什么我收到这个错误。在Firebug中工作正常。

function init() {
updateClock ();
};


function updateClock ( )
{
  var currentTime = new Date ( );
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );
  // Pad the minutes and seconds with leading zeros, if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
  // Choose either "AM" or "PM" as appropriate
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;
  // Compose the string for display
  currentTimeString = currentHours + ":" + currentMinutes + " " + timeOfDay; 
  // Update the time display
  document.getElementById("time").innerHTML = currentTimeString;
}

currentTimeString = "";
window.addEventListener("load", init(), false);

以下是它在html中的实现方式:

<body>
<p id="time">&nbsp;</p>
</body>

2 个答案:

答案 0 :(得分:10)

window.addEventListener("load", init(), false);

此行立即调用init 并将结果传递给addEventListener(就像任何其他函数调用一样)。

您希望在不调用它的情况下传递函数。

答案 1 :(得分:4)

更改行

window.addEventListener("load", init(), false);

window.addEventListener("load", init, false);

原因是您在原始代码中调用init()函数(并将返回值传递给addEventListener)。您需要传递函数init(变量)。