我用Javascript代码构造了一个小时钟,但无法正确更新。它显示的时间很好,但您必须刷新页面才能使时钟正确更新。有没有办法让我的代码自动更新,而不必每次都更新页面?
照片:
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
</script>
答案 0 :(得分:2)
首先,你可以将代码包装在一个函数中,比如currentTime()
,将document.write
调用更改为return语句,这样你就有一个函数currentTime()
返回更新字符串。然后将句柄保存到要显示更新时间的HTML元素的句柄,例如el = document.getElementById('time')
,然后使用这样的间隔
setInterval(function () {
el.innerHTML = currentTime();
}, 5000);
答案 1 :(得分:1)
function UpdateClock(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
//document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
document.getElementById('myClock').innerHTML = "<b>" + hours + ":" + minutes + " " + suffix + "</b>";
}
setInterval(function(){ UpdateClock(); }, 6000);
<强> HTML:强>
<div id="myClock"></div>