我想要一个 30 分钟的倒数计时器。我在 2 个地方(我网站的顶部和底部)插入了这个计时器。两个计时器具有相同的代码。但只有 1 个计时器工作,另一个不显示。为什么会这样?代码有问题吗?
你能展示一个不同的代码来实现相同的结果,没有任何错误。
function countdown() {
time = parseInt(localStorage.time);
if (isNaN(time) || time > (30*60)) {
//alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 30 * 60;
countdown();
return null;
}
if (time <= 0) {
//alert("Your Timer Has Run Out! We Still Got 2 Copies Left, You Could Still Try!");
return null;
}
document.getElementById('timeleft').innerText = formatTime(time);
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
function formatTime(time) {
minutes = Math.floor(time / 60);
seconds = time - minutes * 60;
if (String(seconds).length == 1) {
return String(minutes) + ":0" + String(seconds);
}
return String(minutes) + ":" + String(seconds);
}
countdown();
<font size="+26"><div id="timeleft"></div></font>
这可能是因为您使用 ID 来引用计时器容器。当您使用 时getElementById
,您将始终获得具有相应 ID 的第一个元素。
使用原始 javascript(没有像 jQuery 这样的任何框架),您可以使用类似getElementsByClassName() 的东西,它会返回特定类的所有发生率。
例子:
1)class
改用属性id
:
<div class="timeleft"></div>
您的实现可以是这样的:
var timers = document.getElementsByClassName('timeleft');
Array.prototype.forEach.call(timers, function(timer) {
timer.innerText = formatTime(time);
})
编辑:这是适用于您的代码的解决方案:
function countdown() {
time = parseInt(localStorage.time);
if(isNaN(time) || time > (30 * 60)) {
//alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 30 * 60;
countdown();
return null;
}
if(time <= 0) {
//alert("Your Timer Has Run Out! We Still Got 2 Copies Left, You Could Still Try!");
return null;
}
var timers = document.getElementsByClassName('timeleft');
Array.prototype.forEach.call(timers, function(timer) {
timer.innerText = formatTime(time);
})
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
function formatTime(time) {
minutes = Math.floor(time / 60);
seconds = time - minutes * 60;
if(String(seconds).length == 1) {
return String(minutes) + ":0" + String(seconds);
}
return String(minutes) + ":" + String(seconds);
}
window.onload = function() {
countdown();
}
您可以使用散布在代码中的这 2 个(或更多)标签来测试解决方案:
<div class="timeleft"></div>
<div class="timeleft"></div>
我的测试预览:
按照这种方法,您可以在页面中添加所需的计时器数量,而无需进行 javascript 更改:)
PS:你应该看看jQuery。它可以让你的生活更轻松,拥有更干净的实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句