我想要显示两个时钟,目前只有一个时钟:
<script type="text/javascript">
var tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
function GetClock(){
var d=new Date();
var nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds();
if(nmin<=9) nmin="0"+nmin
if(nsec<=9) nsec="0"+nsec;
document.getElementById('clockbox').innerHTML=" "+ndate+" "+tmonth[nmonth]+" "+nyear+", "+nhour+":"+nmin+":"+nsec+"";
}
window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
<div id="clockbox"></div>, <script type="text/javascript" src="js/rs-clock.js"></script>
第二个时钟(rs-clock.js)的脚本如下:
function startTime() {
var today=new Date();
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('rs-clock').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
我必须同时加入.js并添加它,如果是的话我该怎么做?
答案 0 :(得分:1)
如果您希望显示多个时钟,则当前解决方案存在一些问题。每个元素都需要拥有自己的实例,每个元素都需要是变量下的唯一对象。为此,我建议给时钟一个类名,然后在这些上运行for循环来设置主时间函数。最后,因为它是一个时钟我建议使用setInterval
而不是setTimeout
,以便您可以确保它每秒运行一次。当然,使用i
//make sure this is in some kind of onload function
elems = document.getElementsByClassName("clocks");
for (var i = 0; i < elems.length; i++) {
(function(i) { //this puts each set interval in its own unique instance
var temptime = elems[i]; //save the clock variable in this instance
setInterval(function() {
var today=new Date();
var h=today.getUTCHours();
var m=today.getUTCMinutes();
var s=today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
temptime.innerHTML = h+":"+m+":"+s;
}, 1000);
}(i));
}
工作的jsfiddle:https://jsfiddle.net/krz2feqd/
我拿了你的第一个时钟并在0的唯一实例下将它实现到这个循环中。这是一个jsfiddle:https://jsfiddle.net/pbp5scuL/