简体   繁体   中英

How to make this Javascript function work for more elements

I have this 'building' feature I've been working on and I ran into a problem. When you push a certain button, a timer will be shown to the user. This actually works just fine. However, when another button of the same category is pushed, the timer will only show up for the first one as you can see at this picture

All those buildings are being looped from the database. Within this loop is the Javascript function that shows the timer. (Using Jquery countdown).

Is there anyone who could show me how to make this countdown timer loop correctly as well?

This is the timer part within the PHP loop:

<button class="btn btn-disabled" type="button">Workers are currently working on this property</button>
<span>Time untill completion: <span id="cd" data-countdown-id="<?php echo $userrow['building_id']; ?>" data-countdown="<?php echo $timedifference->format("%H:%I:%S"); ?>"></span> </span>

<script>
    $(function createCountDown() {
     var cd = document.getElementById("cd")
     var countdown = cd.getAttribute("data-countdown")
     var cdid = cd.getAttribute("data-countdown-id");
     $('#buycd' + cdid).countdown({
         until: countdown
     });
 });
 </script>

<div id="buycd<?php echo $userrow['building_id']; ?>"></div>

If you need to see more of the code, please tell me.

PS: If I only start one timer, it works fine on any of them.

You are using cd as the id, but from your comment, that is being applied to multiple elements. Elements must have unique ids (or no id). So you should use a class for this eg class="cd" .

then you code looks like:

$(function createCountDown() {
     $('.cd').each(function(){
        var countdown = $(this).attr('data-countdown');
        var cdid = $(this).attr('data-countdown-id');
        $('#buycd' + cdid).countdown({
          until: countdown
        });
     })     
 });

I didn't test that snippet... expect bugs :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM