我正在尝试在页面上为foreach
语句的每个循环设置一个倒数计时器。目前,它似乎只显示在最后一个循环中。
这是我的foreach
:
@foreach($top4auctions as $auction)
<div class="span3">
<a href="/auction/{{ $auction->id }}"><u><strong>{{ $auction->item }}</strong></u>
<br />
Current Price: ${{ $auction->price }}
<div class="span8">
<img src="{{ $auction->itempic }}" alt="{{ $auction->item }} CS:GO Skin Auction"></a>
<br />
<div class="clock{{ $auction->id }}"></div>
<script>
window.onload = function () {
var fiveMinutes{{ $auction->id }} = 60 * 5,
display = document.querySelector('.clock{{ $auction->id }}');
startTimer(fiveMinutes{{ $auction->id }}, display);
};
</script>
</div>
</div>
@endforeach
这是startTimer
的代码:
<script type="text/javascript">
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
</script>
我根据$auction->id
命名了所有内容,但它仍然无法正常工作..所以我现在不知道该怎么做。
答案 0 :(得分:2)
不要在每个循环中覆盖window.onload,请尝试以下
<script>
window.addEventListener('load', function() {
var fiveMinutes {
{
$auction - > id
}
} = 60 * 5,
display = document.querySelector('.clock{{ $auction->id }}');
startTimer(fiveMinutes {
{
$auction - > id
}
}, display);
});
</script>