【问题标题】:Showing countdown timer on each foreach在每个 foreach 上显示倒数计时器
【发布时间】:2015-09-23 05:05:36
【问题描述】:

我试图在页面上为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-&gt;id 命名了所有内容,但它仍然无法正常工作。所以我现在不知道该怎么办。

【问题讨论】:

  • 您在每个循环中都覆盖了 window.onload 函数,因此为什么只有“最后一个循环”有效

标签: javascript laravel laravel-5


【解决方案1】:

与其在每个循环中覆盖 window.onload,不如尝试以下方法

 <script>
    window.addEventListener('load', function() {
        var fiveMinutes{{ $product->id}} = 60*5,
        display = document.querySelector('.clock{{ $product->id }}');
        startTimer(fiveMinutes{{$product->id}}, display);
    });
</script>

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    相关资源
    最近更新 更多