HTML如下:
<div>
<div id = "date"></div>
<div id = "day"></div>
<div id = "time"></div>
? ?<div id = "timestr"></div>
</div>
js如下:
function setDMY()
{
var dateOb =new Date();
var d = checklen(dateOb.getMonth() + 1)+"."+checklen(dateOb.getDate())+"
."+dateOb.getFullYear().toString();
document.getElementById("date").innerHTML = d;
var d2 = getCHday(dateOb.getDay() + 1);
document.getElementById("day").innerHTML = d2;
var obj = get12Hours(dateOb.getHours());
var time = checklen(obj.h) + ":" + checklen(dateOb.getMinutes()) +":" +
checklen(dateOb.getSeconds());
document.getElementById("time").innerHTML = time;
document.getElementById("timestr").innerHTML = obj.str;
setTimeout("setDMY()",1000);
}
function checklen(da)
{
if(da.toString().length == 1)
return "0" + da.toString();
else
return da.toString();
}
function getCHday(day)
{
switch(day)
{
case 1:return "星期一";
case 2:return "星期二";
case 3:return "星期三";
case 4:return "星期四";
case 5:return "星期五";
case 6:return "星期六";
case 7:return "星期日";
}
}
function get12Hours(hours){
var obj = new Object();
if(hours > 12)
{
obj.h = hours - 12;
obj.str = "pm";
}
else
{
obj.h = hours;
obj.str = "am";
}
return obj;
}
setDMY();
-----------------------------------
如上面的这样运行是正常的,一个时钟(12小时制的)。可是我如果把HTML改成如下:
<div>
<div id = "date"></div>
<div id = "day"></div>
<div id = "time"><span id = "timestr"></span》</div>
</div>
这样就出错了,timestr在页面中没掉了,并且时钟还不会动了。
不知道是什么原因,是因为id冲突了吗??
document.getElementById("time").innerHTML = time; 时,<span id="timestr"></span> 没了。
document.getElementById("timestr").innerHTML = obj.str;innerHTML把<span id="timestr"></span>给替换了所以页面没有timestr了
document.getElementById("time").innerHTML = time;
document.getElementById("timestr").innerHTML = obj.str;
换成
document.getElementById("time").innerHTML = "<span>"+time+"</span><span id = 'timestr'></span>";
document.getElementById("timestr").innerHTML = obj.str ;