1.在一个div里面显示当前时间
用id选择器
<html>
<head>
<meta charset="utf-8">
<title>当前时间</title>
<script type="text/javascript">
var t = null;
function time() {
dt = new Date();
var y = dt.getFullYear();
var M = dt.getMonth() + 1;
var d = dt.getDate();
var h = dt.getHours();
var m = dt.getMinutes();
var s = dt.getSeconds();
M=checkTime(M);
d=checkTime(d);
h=checkTime(h);
m=checkTime(m);
s=checkTime(s);
document.getElementById("timeShow").innerHTML = "当前时间:" + y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;
t = setTimeout(time, 1000);
}
window.onload = function () {
time()
}
function checkTime(i){
if(i<10){
i="0"+i;
}
return i;
}
</script>
</head>
<body>
<div id="timeShow"></div>
</body>
</html>
显示结果:
2.如果多个div显示当前时间的话
用class选择器
<html>
<head>
<meta charset="utf-8">
<title>当前时间</title>
<script type="text/javascript">
var t = null;
function time() {
dt = new Date();
var y = dt.getFullYear();
var M = dt.getMonth() + 1;
var d = dt.getDate();
var h = dt.getHours();
var m = dt.getMinutes();
var s = dt.getSeconds();
M=checkTime(M);
d=checkTime(d);
h=checkTime(h);
m=checkTime(m);
s=checkTime(s);
$('.timeShow').html(y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s);
t = setTimeout(time, 1000);
}
window.onload = function () {
time()
}
function checkTime(i){
if(i<10){
i="0"+i;
}
return i;
}
</script>
</head>
<body>
<div class="timeShow"></div>
<div class="timeShow"></div>
<div class="timeShow"></div>
</body>
</html>