javascript 中的 SetInterval 重复显示而不是更改

SetInterval in javascript displays repeatedly instead of change

我做了一个倒计时,将显示在 table 列中,但它是重复列而不是列中的更改。

该片段将有助于更好地理解问题:(已编辑)

var countDownDate = new Date("Apr 29, 2019 23:56:26").getTime();
var table = document.getElementById("test");
// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now an 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);


  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  cell1.innerHTML = days + "d " + hours + "h "
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
  }
}, 1000);
.timer_bg {
  background-color: red;
  color: white;
}
<table id="test" class="table table-bordered table-responsive">

</table>

倒计时效果很好,它也在减少,每一秒它都在生成一列,我不希望这样。

更新

还有如何在该行中添加 class timer_bg

将行和单元格的创建移到 setInterval 之外。

var row = table.insertRow(0);
var cell1 = row.insertCell(0);
setInterval(...)

将 class 添加到行中,如下所示:

row.className = 'timer_bg';

最简单的解决方案是创建一个固定的 table 并将更改的时间注入到固定的元素中。

无需创建 table 行和单元格。你可以把它放在原来的 HTML.

更新 1

如果你真的需要动态创建元素,你应该在 setInterval 函数之外创建这个元素(致谢 )。您还可以在那里添加您的 class 姓名。

var countDownDate = new Date("Apr 29, 2019 23:56:26").getTime();
var table = document.getElementById("targetTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);

// Create a "class" attribute
var att = document.createAttribute("class");
att.value = "timer_bg";
cell1.setAttributeNode(att);

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now an 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);

  cell1.innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
  }
}, 1000);
<table id="targetTable">
</table>