我正在尝试在页面上刷新日期,因此我不必每天手动刷新它。我已经有了这个代码,但它似乎并没有起作用。日期显示,但是当日期发生变化时,它不会更新。作为参考,这用于BrightSign显示器。谁能告诉我我做错了什么?我是一个JavaScript初学者,所以没有太复杂了:)
<script type="text/javascript">
<!--
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
setInterval(clockTick, 1000);
return (month + "/" + day + "/" + year);
}
document.write(clockTick());
//-->
</script>
答案 0 :(得分:1)
您需要从函数中取出setInterval
并在函数内的页面上设置时间,以便每秒刷新一次:
function clockTick() {
var currentTime = new Date(),
month = currentTime.getMonth() + 1,
day = currentTime.getDate(),
year = currentTime.getFullYear(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
seconds = currentTime.getSeconds(),
text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds);
// here we get the element with the id of "date" and change the content to the text variable we made above
document.getElementById('date').innerHTML = text;
}
// here we run the clockTick function every 1000ms (1 second)
setInterval(clockTick, 1000);
&#13;
<span id="date"></span>
&#13;
答案 1 :(得分:0)
你可以试试这个:从外面打电话给clockTick()
。
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
// alert("hi");
document.getElementById('date').innerHTML=month + "/" + day + "/" + year;
}
setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>