JavaScript倒计时计时器出现2个错误

Getting 2 errors with a JavaScript Countdown Timer

本文关键字:2个 错误 倒计时 计时器 JavaScript      更新时间:2023-09-26

我创建了一个倒数计时器,每天倒数到下午5点,然后在第二天重置到下午5点。

计时器工作完美,但我从我正在努力解决的代码中得到2个错误。

代码如下:

    function startTimer(display) {
    var date = new Date();
    var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
    if(date.getHours() >= 17) {
        h17.setDate(h17.getDate()+1);
    }
    h17 = h17.getTime();
    var diff,
        hours,
        minutes,
        seconds;
    function timer() {
        diff = (((h17 - Date.now()) / 1000) | 0);
        // Setting and displaying hours, minutes, seconds
        hours = (diff / 3600) | 0;
        minutes = ((diff % 3600) / 60) | 0;
        seconds = (diff % 60) | 0;
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = hours + ":" + minutes + ":" + seconds;
    };
    timer();
    setInterval(timer, 1000);
}
window.onload = function () {
    var display = document.querySelector('#time');
    startTimer(display);
};

错误如下:第14行:diff = (((h17 - Date.now()) / 1000) | 0);

返回消息:"对象不支持此属性或方法:第14行"

和第25行:display.textContent = hours + ":" + minutes + ":" + seconds;

返回消息"Cannot set property 'textContent' of null"

原来问题来自于将输出绑定到html中的#time ID。

由于我把脚本放在,只在某些页面上使用它,错误来自没有<div id="time">的页面,所以显示为空。

在运行脚本之前,我已经通过检查元素ID是否存在来修复这个问题。

if(document.getElementById("time")){
        var display = document.querySelector('#time');
        startTimer(display);
    } else {
    }