如何定期更新时间? [英] how to update time regularly?
本文介绍了如何定期更新时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now);给我每一秒的价值,但它没有在html更新。如何更新html上的时间,而不刷新页面?
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
推荐答案
你的代码有一些错误。不使用变量声明的 var
infront,则将它们泄漏到全局范围中。
There are a number of mistakes in your code. Without the use of var
infront of your variable declarations, you leak them into the global scope.
Also, the use of document.write
is discouraged.
以下是我将如何做:
JavaScript
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
<div id="time"> </div>
这篇关于如何定期更新时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文