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

Eri*_*ran 0 html javascript

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);
Run Code Online (Sandbox Code Playgroud)

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

<body>
<p id="time">&nbsp;</p>
</body>
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 10

window.addEventListener("load", init(), false);
Run Code Online (Sandbox Code Playgroud)

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

你想要传递函数本身,而不是调用它.