gpt4 book ai didi

JavaScript 计时器 : Code Working Uncaught TypeError

转载 作者:行者123 更新时间:2023-11-30 12:22:48 24 4
gpt4 key购买 nike

我在页面上使用 javascript 计时器,它会在有限的时间后重定向用户。该代码完全符合我的要求,但它继续在控制台中抛出错误。我收到的错误信息是

Uncaught TypeError: Cannot set property 'textContent' of null

 //Countdown Timer

function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}

CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;

(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);

if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}

obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};

CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};

CountDownTimer.prototype.expired = function() {
return !this.running;
};

CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};

window.onload = function() {

var display = document.querySelector(".cdtimer"),
s6timer = new CountDownTimer(20);

s6timer.onTick(format).onTick(redirect).start();

function redirect() {
if (s6timer.expired()) {
window.location.replace("../assessmentportal/sectiontimeout.php");
}
};

function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
};
};

});

最佳答案

发生这种情况是因为此调用 document.querySelector(".cdtimer") 返回 null。有两个可能的原因:

  1. 没有类名为cdtimer

    的元素
  2. 您正在 DOM 加载之前运行您的脚本

关于JavaScript 计时器 : Code Working Uncaught TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30461804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com