我的标题中包含以下代码:
<script type="text/javascript">
function ShowTimes() {
var now = new Date();
var hrs = 23-now.getHours();
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str += '<b><span style="color:#FF9600;">Discount Ending:</span> <span style="color:#489FDC;">'+hrs+' Hours '+mins+' Minutes '+secs+' Seconds</span></b>';
document.getElementById('countdownToMidnight').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
</script>
我把它添加到我的身体标签:
<body id="homepage" onload="_cntDown=setInterval('ShowTimes()',1000)">
然后我只需在想要倒计时的地方添加它:
<div id="countdownToMidnight"></div>
问题在于,如果我将<div id="countdownToMidnight"></div>
放在页面上的2个位置,则只显示第二个位置。在代码中是否存在导致这种情况发生的错误?
答案 0 :(得分:1)
ID
应该是唯一的,请尝试使用class
,例如:
<div class="countdownToMidnight"></div>
和js改变:
document.getElementById('countdownToMidnight').innerHTML = str;
到
var divEle = document.getElementsByClassName('countdownToMidnight');
for(var d = 0,len = divEle.length; d < len; d++) {
divEle[d].innerHTML = str;
}