如何在具有相同类名的不同 div 上运行 JavaScript 计时器



我在堆栈流上搜索了我的问题,但无法得到合适的答案。我有由后端代码循环生成的框。这个盒子在各个盒子倒计时后被销毁。时间范围与后端框的内容一起提供。现在,根据我的后端代码的结果,盒子可以是 10 或 100 万,视情况而定。所以我在循环中对它们中的每一个运行了一个 jquery 倒数计时器。问题是第一个盒子的倒计时用于所有其余盒子,所以当第一个盒子的计时器结束时,销毁命令会影响所有盒子。

下面是我使用 Laravel 刀片语法所做的事情的示例。

@forelse($boxe_deatails as $box_detail) 
<div class="box-v2-detail-o">
<div class="col-md-16 col-xs-6 pull-right" style="background: rgba(110, 151, 170, 0.57);min-width: 100%;min-height: 73px;float: right;padding: 10px;font-size: small;line-height: 2em;margin: 5px;">
Timer to Run
<div id="timer">
@include('partials/count-timer')
</div>
</div>
<img style="width: 60px;height: 60px;border: 3px solid #fff;" src="{{asset('asset/img/avatar.jpg')}}" class="img-responsive"/>
<h4>Name {{$box_detail->name}} </h4>
<big>Size {{ $box_detail->size}} </big>
</div> 
@empty
hello Empty
@endforelse

这就是循环。那些数据是从我的数据库中获取的。

count timer file am using jquery.countdown-2.2.0 所以我所要做的就是选择目标 DOM 元素并在其上运行计时器动画。

<script type="text/javascript">
$('body').find("div#timer").countdown('{{$box_detail->created_at->addHours(13)}}', {elapse:true}).on('update.countdown', function(event) {
$(this).text(event.strftime('%H Hr(s) : %M Min(s) : %S Sec(s)'));
if (event.elapsed) {
$.ajax({
url     : '{{url('/timer-delete-box/'.$box_detail->id)}}',
method  : 'get',
success : function(response)
{ 
alertify.notify('You did not make your payment before time. So your account has been pause', 'error', 9)
} 
})
}
});
</script>

所以现在的问题又是,即使计时器不同,第一个盒子的倒计时也用于所有盒子,我希望计时器在每个盒子上运行。 同样,第一个的计时器功能在所有盒子上重复,而循环的时间是不同的。当你查看它时,你会看到一个统一的时间,这是非常错误的。请有人帮我修复它.

现在我知道问题是该函数只运行一次,那么如何根据循环计数多次调用它。

我认为如果实现您问题的答案,它应该看起来像这样。

$('div#timer').each(function() {

var $this = $(this), 
finalDate = '{{$box_detail->created_at->addHours(13)}}';
$this.countdown(finalDate,  {elapse:true}).on('update.countdown', function(event) {
$this.text(event.strftime('%H Hr(s) : %M Min(s) : %S Sec(s)'));
if (event.elapsed) {
$.ajax({
url     : '{{url('/time-pause-account/'.$Topay->id)}}',
method  : 'get',
success : function(response)
{ 
alertify.notify('You did not make your payment before time. So your account has been pause', 'error', 9,  function(){
$('body').css({
'opacity' : '0',
'transition' : 'all 1s'
})
$('body').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
window.location = 'home'
})
})
} 
})
}
});
});

我已经找到了问题的解决方案,我所要做的就是对盒子使用每个j查询循环。 在问这个问题之前,我最初是这样做的,但是我将倒计时连接到每个函数,直到我看到多个实例的倒数计时器的文档。 他们仍然使用 each 循环,但没有将倒计时 obj 连接到它。 链接到我问题的答案

最新更新