我正在尝试在此网站上显示日期和时间,现在您必须刷新页面以便更新(秒等)。如何自动更新秒数?
<!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>
答案 0 :(得分:2)
将更新逻辑包装在一个函数中,并每1000ms调用一次:)
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);
答案 1 :(得分:1)
HTML
<span class="clock"></span>
的Javascript
jQuery(function($) {
setInterval(function() {
var date = new Date(),
time = date.toLocaleTimeString();
$(".clock").html(time);
}, 1000);
});
答案 2 :(得分:0)
这适用于我的网站。使用setInterval函数
$(document).ready(function(){
set_time()
window.setInterval(function(){set_time()}, 1000)
});
function set_time(){
time = $('#time')
raw_time = new Date();
real_time = raw_time.getFullYear() + "-" + (raw_time.getMonth() + 1) + "-" + raw_time.getDate() + " " + (raw_time.getHours()-12) + ":" + raw_time.getMinutes() + ":" + raw_time.getSeconds();
time.html(real_time)
}
答案 3 :(得分:0)
使用完全符合您要求的setTimeout
,here is a neat little script
答案 4 :(得分:0)
使用纯javascript和更新<span>
元素
setInterval(function() {
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.getElementById("clock").innerHTML = "<b><div id='d1'>" + hours + ":" +
minutes + ":" + seconds + " " + suffix + "</div></b>";
}, 1000);
<span id="clock"></span>