我創建了一個計時器,並沒有注意到document.write正在殺死頁面,因爲一切都很好。但是,當計時器變爲0時,它只顯示document.write函數中的內容,而不顯示頁面中的所有內容。document.write正在查殺頁面
這就是殺死頁面,只有文字()的是什麼是顯示..
document.write("The NFL Season is here!!");
我怎樣才能讓這個使計時器將停止這個文本顯示或本文本可以顯示在我的頁面上而不會終止其他代碼?
這裏是我的完整代碼來演示我如何做到這一點。
<script type="text/javascript">
function cdtd() {
var nflSeason = new Date ("September 10, 2015 08:30:00");
var now = new Date();
var timeDiff = nflSeason.getTime() - now.getTime();
if (timeDiff < 0) {
clearTimeout(timer);
document.write("The NFL Season is here!!");
//Run any code needed for countdown completion here.
}
var seconds = Math.floor(timeDiff/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd()',1000);
}
</script>
HTML
<div class="countdown_out">
<div id="countdown_title">NFL Season Opener Countdown</div>
<div class="countdown_position">
<div class="countdownBox">
<div class="countdown_time_category">Days</div>
<div id="daysBox" class="countdown_time"></div>
</div>
<div class="countdownBox">
<div class="countdown_time_category">Hours</div>
<div id="hoursBox" class="countdown_time"></div>
</div>
<div class="countdownBox">
<div class="countdown_time_category">Minutes</div>
<div id="minsBox" class="countdown_time"></div>
</div>
<div class="countdownBox">
<div class="countdown_time_category">Seconds</div>
<div id="secsBox" class="countdown_time"></div>
</div>
</div>
[相關 - document.write()是什麼損害?](http://stackoverflow.com/questions/2559189/what-damage-is-done-by-document-write) –
這是*爲什麼你不應該使用'document.write()'。一旦頁面被完全加載,它**破壞所有內容並覆蓋DOM。如果你想寫入DOM,使用'.innerHTML'(或類似的)。 –
P.S.做**不**做'setTimeout('cdtd()',1000)'。這使用'eval',這是非常糟糕的做法。相反,'setTimeout(cdtd,1000)'。 –