【发布时间】:2011-09-05 11:55:28
【问题描述】:
我正在尝试在<p></p> 标签中包含一个实时时钟。
我的js代码如下:
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
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
位于“date.js”文件中,我已将其包含在 HTML 代码中
HTML 代码是
<p id="clock"> </p>
但没有显示正确... 有什么解决办法吗?
【问题讨论】:
-
您的意思是,您复制了一些代码但没有立即运行,现在希望我们为您调试?我认为如果你告诉我们你尝试了什么,你得到了什么错误信息等等,你会更好。
-
你在任何地方都调用函数
updateClock()吗? -
jsfiddle.net/QvuES 至少它适用于 Google Chrome 和 IE9。 1. 使用控制台检查错误 2. 将
firstChild.nodeValue更改为innerText -
,取自与上述函数相同的页面
标签: javascript html date