倒计时器:无法设置null的属性'textContent'

问题描述 投票:0回答:1

我用一个小倒计时脚本得到了一些错误。在这里找不到解决方案。错误消息每秒产生1个错误:

Uncaught TypeError: Cannot set property 'textContent' of null
at (index):181
(anonymous) @ (index):181
setInterval (async)
(anonymous) @ (index):179

这是计时器的脚本:

<script type="text/javascript">

var timeleft = 45;
var downloadTimer = setInterval(function(){

timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
document.getElementById("countdowntimer").style.color = "white";

if(timeleft <= 0)
    clearInterval(downloadTimer);
},1000);

</script>
javascript timer web countdown
1个回答
0
投票

您的HTML(根据您的评论)无效(</span class="timer">)。此外,代码可以简化。

countDownForNOfTicks(5);

function countDownForNOfTicks(nOfTicks) {
  document.querySelector("#countdowntimer").textContent = nOfTicks--;
  // [do more things if necessary]
  if (nOfTicks >= 0) {
    return setTimeout(() => countDownForNOfTicks(nOfTicks), 1000);
  }
  return refresh();
}

function refresh() {
  document.querySelector("div.timer").textContent += " DONE";
}
<div class="timer">Refreshing in 
 <span id="countdowntimer">45</span> seconds
</div>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.