如何在php中显示多个倒计时器

时间:2016-01-05 03:03:57

标签: javascript php timer

事实上,我从数据库中选择所有数据时间,但是当显示到页面时,只有前一项会显示计时器,其他项目则无法显示计时器。

 <?php
     $stmtAuction = $db->prepare("SELECT * FROM auction WHERE expired_at >= CURDATE() AND status = 'available' ORDER BY expired_at ASC");
                    $stmtAuction->execute();
     if ($stmtAuction->rowCount() > 0) {
                        while ($item = $stmtAuction->fetch()) {
       ?>
          <span id='countdown' value='<?php echo $item['expired_at'];?>'></span>       

<?php
}
?>
    <script>

     $("#countdown").countdown($('#countdown').attr('value'), function(event) {
                $(this).text(
                    event.strftime('%D days %H:%M:%S')
                );
            });
    </script>

我怎样才能显示每个项目的计时器?

1 个答案:

答案 0 :(得分:2)

您的问题是由非唯一id引起的。您有$stmtAuction->rowCount()id='countdown'id应该是唯一的。所以javascript / jQuery只能找到1st / unique id='countdown'。您需要使用class='countdown'代替 -

<?php
    $stmtAuction = $db->prepare("SELECT * FROM auction WHERE expired_at >= CURDATE() AND status = 'available' ORDER BY expired_at ASC");
    $stmtAuction->execute();
    if ($stmtAuction->rowCount() > 0) {
        while ($item = $stmtAuction->fetch()) {
        ?>
            <span class='countdown' value='<?php echo $item['expired_at'];?>'></span>
                  ^^^^^-change from id to class
<?php
        }
    }
    ?>

现在,在您的javascript中,您需要使用类选择器 - $(".countdown") - 并使用$.each()遍历每个类。

<script>
    $('.countdown').each(function(){
        $(this).countdown($(this).attr('value'), function(event) {
            $(this).text(
                event.strftime('%D days %H:%M:%S')
            );
        });
    });
</script>

jsFiddle example - https://jsfiddle.net/smh5nhgz/1/