使用 JavaScript 倒数计时器出现 2 个错误
Getting 2 errors with a JavaScript Countdown Timer
我创建了一个倒数计时器,每天倒数到下午 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);
返回消息:"Object doesn't support this property or method: line 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 {
}
我创建了一个倒数计时器,每天倒数到下午 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);
返回消息:"Object doesn't support this property or method: line 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 {
}