在循环中,innerHTML只插入最后一个被调用的元素



我试图在几个具有相同类的div标记中显示倒计时。
但是问题是只有列表的最后一个标签包含倒计时。

代码如下:

const contentsDownDate = document.querySelectorAll(".countDown");
nbElement = contentsDownDate.length - 1;
for (var i = 0; i < nbElement; i++) {
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
// Update the count down every 1 second
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"
contentsDownDate[i].innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
contentsDownDate[i].innerHTML = "EXPIRED";
}
}, 1000);
}

我通过调用id做了同样的事情,但仍然是相同的结果,只有最后一个id显示倒计时。

我能做什么来解决这个问题?

请注意,倒计时代码取自:w3schools

PS:我还读到innerHTML在循环结束时打印,所以它只打印最后一个标签,所以你必须停止/暂停循环才能打印,特别是setInterval,但我已经这样做了。除非这个是为了更新倒计时时间?但是在这种情况下,我应该把另一个setInterval放在哪里?

这不起作用的原因是您在阻塞状态下进入无限循环,这意味着在浏览器忙于循环时永远不会输入间隔。想象一下,浏览器一次只能做一件事,就像在一个线程中一样,所以循环就是它,在它完成之前不能做任何其他事情,在你的例子中,它永远不会。

基本上,如果你在循环中不清除setInterval(),那么setInterval就不会停止,这意味着循环是无限的,所以它永远不会完成。

相反,将循环放入setInterval()中就可以完成这项工作。让我们试试这个:

const contentsDownDate = document.querySelectorAll(".countDown");
nbElement = contentsDownDate.length-1;
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
// Update the count down every 1 second
x = setInterval(function() {
for (i=0; i<=nbElement; i++){
// 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"
contentsDownDate[i].innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
contentsDownDate[i].innerHTML = "EXPIRED";
}
}
}, 1000);

最新更新