javascript - getElementById(...) 为空。在 Firebug 中工作正常

标签 javascript html

类型错误:document.getElementById(...) 为空。 不知道为什么我会收到此错误。在 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>

最佳答案

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

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

您想要传递函数本身,而不调用它。

关于javascript - getElementById(...) 为空。在 Firebug 中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16902370/

相关文章:

html - 您应该如何对文本区域的内容进行编码

javascript - 理解异步和等待

javascript - Vuetifys 在工具栏中添加单独的文本字段失败

javascript - 在Javascript中获取多维数组中元素的坐标

javascript - flexbox 是否可以通过文本换行捕捉到网格?

单击事件的 Javascript 问题

html - 如何在多个文件中使用基本的html代码结构

javascript - 是什么促使 chrome devtools 寻找源图

jquery - 重置响应功能

javascript - 如何在 AngularJS 中排序时删除重复值?