我一直收到错误说:无法设置属性&inner;内部HTML' null。
我尝试更改innerHTML - > innerText。仍然没有工作。
我在这里缺少什么?
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1;
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by
Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(3);
HTML
<div id="timer"></div>
答案 0 :(得分:1)
您正在呼叫countdown()
,呼叫tick()
,在该元素被解析之前调用document.getElementById("timer")
, 。
尝试这样做:
<div id="timer"></div>
<script type="text/javascript">
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1) {
// countdown(mins-1);
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(3);
</script>
在这种情况下,订单很重要。在通过DOM访问文档之前,您需要确保文档遇到该元素。