同一页面多个倒计时

Multiple countdown in same page

我需要一些有关 javascript 代码的帮助,我尝试获取适用于同一页面上的多个倒数计时器的代码。我尝试了下面的代码但没有成功。

    <div class="expirydiv">Jan 02,2019</div>
    <div class="expirydiv">jun 15,2019</div>

    <script>
// Set the date we're counting down to

          var ps = document.querySelectorAll("div.expirydiv");

          var countDownDate = new Date(ps).getTime();

// Update the count down every 1 second

          var x = setInterval(function() {

// Get today's date and time

          var now = new Date().getTime();

// Find the distance between now and the count down date

          var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds

          var days = Math.floor(distance / (1000 * 60 * 60 * 24));

          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);



// Output the result in an element with classname="expirydiv"

    for(var i=0; i<ps.length; i++){
      ps[i].innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";

// If the count down is over, write some text

      if (distance < 0) {
        clearInterval(x);
        ps[i].innerHTML = "EXPIRED";
      }
      }
    }, 1000);

    </script>

上面代码的结果如下所示:

    NaNd NaNh NaNm NaNs
    NaNd NaNh NaNm NaNs

这段代码有什么问题,我认为查询 select 或未能将 select 和 div.expirydiv 作为日期。

var countDownDate = new Date(ps).getTime();更改为var countDownDate = new Date(ps[0].innerHTML).getTime();

您正在使用多个倒计时,因此您需要遍历它们并设置计时器。

var ps = document.querySelectorAll("div.expirydiv");
ps.forEach(function(timer){
    var countDownDate = new Date(timer.innerText).getTime();

    var x = setInterval(function() {

        var now = new Date().getTime();
        var distance = countDownDate - now;
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));

        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);    

            timer.innerHTML = days + "d " + hours + "h "
            + minutes + "m " + seconds + "s ";
            if (distance < 0) {
                clearInterval(x);
                timer.innerHTML = "EXPIRED";
              }

    }, 1000);    
});
<div class="expirydiv">Dec 02,2019</div>
<div class="expirydiv">Dec 15,2019</div>