gpt4 book ai didi

javascript - 在标记传单 map 的弹出窗口中插入多个倒计时

转载 作者:行者123 更新时间:2023-12-02 21:00:21 27 4
gpt4 key购买 nike

我的目标是在每个弹出标记上显示基于 Json (obj.time) 的倒计时。倒计时必须显示在 <div id='demo'> 上如果我为所有 <div id='demo'> 插入一个倒计时有效,但不具有多重值(value)。

我尝试将 obj[i].id 连接到 id = 'demo' 以便每个倒计时都有多个 id像这样<div id='demo"+obj[i].id+"'>然后我也做了同样的事情 document.getElementById("demo"+obj[i].id).innerHTML = hours + "h "+ minutes + "m " + seconds + "s ";

我收到的错误是 Uncaught TypeError: Cannot read property 'id' of undefined at (index):215

这是我的项目https://jsfiddle.net/tiziako/wpo32g6a/

最佳答案

您必须在间隔函数中放置一个新循环:

var x = setInterval(function() {
for(var i = 0; i < obj.length; i++){
if(document.getElementById("demo"+obj[i].id)){
// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = new Date(obj[i].time).getTime() - now;

// If the count down is finished, write some text and continue loop
if (distance < 0) {
document.getElementById("demo"+obj[i].id).innerHTML = "EXPIRED";
continue;
}
// 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);

// Display the result in the element with id="demo"
document.getElementById("demo"+obj[i].id).innerHTML = hours + "h "+ minutes + "m " + seconds + "s ";

}
}
}, 200);

您还可以更快地设置间隔,然后如果您打开弹出窗口,它会更快地显示计时器。

https://jsfiddle.net/falkedesign/7fkpvzta/

关于javascript - 在标记传单 map 的弹出窗口中插入多个倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61369524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com