JS 页面多次倒计时(getElementsByClassName 不显示)

JS countdown multiple times on page (won't display with getElementsByClassName)

我从 w3 中获取了一些 JS 代码来创建倒计时。 (https://www.w3schools.com/howto/howto_js_countdown.asp)

因为我想在一页上多次显示倒计时,所以我将 getElementById("demo") 更改为 > getElementsByClassName("demo")

不幸的是,这不起作用。什么都没有出现。为什么会这样,我怎样才能多次显示同一个计数器?我尝试了一些事情,但没有成功。这是我的代码:

html

<p class="demo"></p>

js

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2022 15:37:25").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 id="demo"
  document.getElementsByClassName("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementsByClassName("demo").innerHTML = "EXPIRED";
  }
}, 1000);

正如@ShanieMoonlight 提到的,您需要迭代 HTMLCollection。您只需进行最少的调整即可轻松完成。例如。当您使用扩展运算符时,forEach 函数将可用。

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2022 15:37:25").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 id="demo"
  [...document.getElementsByClassName("demo")].forEach(e => e.innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ");
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    [...document.getElementsByClassName("demo")].forEach(e=>e.innerHTML = "EXPIRED");
  }
}, 1000);
<p class="demo"></p>

<p class="demo"></p>

<p class="demo"></p>