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>
警报(现在);每秒给我一个值,但它没有在 html 中更新。如何在不刷新页面的情况下更新 html 上的时间?
最佳答案
您的代码中有许多错误。如果不在变量声明前使用 var
,就会将它们泄漏到全局范围内。
另外,document.write
的使用是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>
关于javascript - 如何定期更新时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091888/