setInterval在.each()内,是否只适用于最后一个间隔



目标:

我使用jQuery的每个函数循环遍历几个.event元素。我正在使用来自每个.event类中隐藏的span元素的信息来计算计时器倒计时。我使用setInterval((每秒重新计算剩余时间。

问题:

我所有的计算都很完美,但只适用于最后一段时间。每个间隔似乎都覆盖了前一个间隔的计算。意思是:只有最后一个.事件得到输出。所有以前的.事件都没有得到任何输出。使用间隔前后的日志,我能够将错误缩小到setInterval函数。如何防止每个间隔覆盖之前的间隔?还是我的错误发生在我还没有想到的地方?

代码:

$('.event').each(function() {
$event = $(this);
// SET FUTURE DATE
$futureDate = $event.find($('.event-time'));
$countdownDate = new Date($futureDate.text()).getTime();
setInterval(function() {

// SET TODAYS DATE
$now = new Date().getTime();

// DIFFERENCE NOW AND FUTURE DATE
$diff = $countdownDate - $now;

// TIME CALCULATIONS FOR d, h, m, s
$days = Math.floor($diff / (1000 * 60 * 60 * 24));
$hours = Math.floor(($diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$minutes = Math.floor(($diff % (1000 * 60 * 60)) / (1000 * 60));
$seconds = Math.floor(($diff % (1000 * 60)) / 1000);

// OUTPUT
$event.find('.clock .val-d').html($days);
$event.find('.clock .val-h').html($hours);
$event.find('.clock .val-m').html($minutes);
$event.find('.clock .val-s').html($seconds);

}, 1000)
});

问题在于,当区间内的函数运行时,循环已经完成,因此$event将只引用jQuery对象中的最后一个.event元素。

假设您可以使用ES6,那么简单的解决方法是使用let关键字来定义$event:

$('.event').each(function() {
let $event = $(this);
// the rest of your code...
});

如果不能使用ES6,则需要使用闭包来保留$(this):的范围

$('.event').each(function() {
(function($event) {
$futureDate = $event.find($('.event-time'));
$countdownDate = new Date($futureDate.text()).getTime();
setInterval(function() {
$now = new Date().getTime();
$diff = $countdownDate - $now;
// TIME CALCULATIONS FOR d, h, m, s
$days = Math.floor($diff / (1000 * 60 * 60 * 24));
$hours = Math.floor(($diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$minutes = Math.floor(($diff % (1000 * 60 * 60)) / (1000 * 60));
$seconds = Math.floor(($diff % (1000 * 60)) / 1000);
$event.find('.clock .val-d').html($days);
$event.find('.clock .val-h').html($hours);
$event.find('.clock .val-m').html($minutes);
$event.find('.clock .val-s').html($seconds);
}, 1000)
})($(this));
});

最新更新