问题
I want to show countdown in each of my divs. Right now I get the seconds from my database and store in in data-countdown attribute and then use the following js code for countdown. Only the first div changes the value every second and the other ones do not change. Here is the fiddle: http://fiddle.jshell.net/j61qs7oc/
//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>
here is the js code
$('[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();
}
});
回答1:
When you declare a variable without using the var
keyword, you're creating a global. So each instance of your countdown is overwriting the previous value of finalDate
, timeout
, and time
. Try adding var
before each of those lines and it should do what you need. i.e.:
var finalDate = $(this).data('countdown');
var $this = $(this);
var timeout = null;
var time = null;
startCountdown($this,finalDate, 1000, end);
回答2:
You could also just do this in regular Javascript instead of 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>
来源:https://stackoverflow.com/questions/34186849/separate-countdown-for-divs