gpt4 book ai didi

javascript - 让秒自动更新?

转载 作者:太空宇宙 更新时间:2023-11-04 16:09:11 27 4
gpt4 key购买 nike

我试图在这个网站上只显示日期和时间,现在你必须刷新页面才能更新它(秒等)。如何让秒数自动更新?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Testbed</title>
</head>
<body>
<h1>
Javascript will find out the date and the browser.
</h1>
<script type="text/javascript">
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var suffix = "AM";

if (seconds < 10)
seconds = "0" + seconds;

if (minutes < 10)
minutes = "0" + minutes;

if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

document.write("<b><div id='d1'>" + hours + ":" +
minutes + ":"+ seconds + " " + suffix + "</div></b>");
</script>
</body>
</html>

最佳答案

将您的更新逻辑包装在一个函数中,并每 1000 毫秒调用一次 :)

function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var suffix = "AM";

if (seconds < 10)
seconds = "0" + seconds;

if (minutes < 10)
minutes = "0" + minutes;

if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

document.write("<b><div id='d1'>" + hours + ":" +
minutes + ":"+ seconds + " " + suffix + "</div></b>");
}

window.setInterval(updateTime, 1000);

关于javascript - 让秒自动更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com