我想在每个div中显示倒计时。现在我从数据库中获取秒数并存储在data-countdown属性中,然后使用以下js代码进行倒计时。只有第一个div每秒更改一次,而其他值不会更改。 这是小提琴: this issue
//imagine this line of code in every loop of a for loop so $remaining will be different
<div style="font-size: 25px; color:#e3b40b ; font-weight: 600;" data-countdown="'.$remaining.'"><i class="fa fa-spinner fa-pulse"></i></div>
这里是js代码
$('[data-countdown]').each(function() {
finalDate = $(this).data('countdown');
var $this = $(this);
timeout = null;
time = null;
startCountdown($this,finalDate, 1000, end);
function startCountdown(display,timen, pause, callback) {
time = timen;
display.html(timen);
if (timen == 0)
callback();
else {
clearTimeout(timeout);
timeout = setTimeout(function () {
startCountdown(display,timen - 1, pause, callback)
}, pause);
}
}
function end() {
alert();
}
});
答案 0 :(得分:4)
如果在不使用var
关键字的情况下声明变量,则需要创建全局变量。因此,倒计时的每个实例都会覆盖先前的finalDate
,timeout
和time
值。尝试在每个行之前添加var
,它应该做你需要的。即:
var finalDate = $(this).data('countdown');
var $this = $(this);
var timeout = null;
var time = null;
startCountdown($this,finalDate, 1000, end);
答案 1 :(得分:0)
您也可以在常规Javascript而不是jQuery中执行此操作...
var countdownDivs = document.querySelectorAll('div[data-countdown]');
function end() {
alert();
}
function countdown(display, timen, pause, callback) {
display.innerHTML = timen;
if (timen == 0) callback();
else {
display.timeout;
clearTimeout(display.timeout);
display.timeout = setTimeout(function () {
countdown(display, timen - 1, pause, callback)
}, pause);
}
}
for(var i = countdownDivs.length>>>0; i--;){
countdown(countdownDivs[i], countdownDivs[i].dataset.countdown, 1000, end);
}
div[data-countdown]{
font-size:25px;
color:#e3b40b;
font-weight:600;
}
<div data-countdown="12312312"></div>
<div data-countdown="555555"></div>
<div data-countdown="95695"></div>