[英]getting error: Cannot set property 'innerHTML' of null
i keep getting error said: Cannot set property 'innerHTML' of null. 我不断收到错误消息:无法将属性'innerHTML'设置为null。
i try to change innerHTML ->innerText. 我尝试更改innerHTML-> innerText。 still not working. 还是行不通。
what am i missing here??? 我在这里想念什么???
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 HTML
<div id="timer"></div>
You're calling countdown()
, which calls tick()
, which calls document.getElementById("timer")
, before that element has even been parsed . 您正在调用countdown()
,该函数调用tick()
,后者甚至在该元素尚未解析之前调用document.getElementById("timer")
。
Try doing it like this: 尝试这样做:
<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>
In this case, order matters. 在这种情况下,顺序很重要。 You want to make sure the document has encountered that element before accessing it via the DOM. 您想确保文档在通过DOM访问该元素之前遇到了该元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.