gpt4 book ai didi

javascript - 如何用倒计时替换特定的div内容

转载 作者:行者123 更新时间:2023-11-30 12:57:13 25 4
gpt4 key购买 nike

我制作了一个从 div 之间获取日期(文本)的脚本:<div class="countdown"> DATE HERE </div>并从中开始倒计时,每 1 秒刷新一次。

我的问题是:如果我有多个 div <div class="countdown"> DATE HERE </div> ,如何让脚本自动从这个 div 创建倒计时。我当前的脚本只有在页面中只有一个这样的 div 时才有效。

这是我的脚本:

var targetDate = $(".countdown").text();
targetDate = new Date(targetDate).getTime();



// porneste counter-ul
setInterval(function() {

var currentDate = new Date().getTime();
var secondsLeft = (targetDate - currentDate) / 1000;


var days = parseInt(secondsLeft / 86400);
secondsLeft = secondsLeft % 86400;

var hours = parseInt(secondsLeft / 3600);
secondsLeft = secondsLeft % 3600;

var minutes = parseInt(secondsLeft / 60);
seconds = parseInt(secondsLeft % 60);


// afiseaza data rezultata
$(".countdown").html('<table cellspacing="0" border="0" cellpadding="0" width="328" align="center"><tr> <td width="82">'+days+'<span class="gray_text">d</span></td> <td width="82">'+hours+'<span class="gray_text">h</span></td> <td width="82">'+minutes+'<span class="gray_text">m</span></td> <td width="82">'+seconds+'<span class="gray_text">s</span></td> </tr></table>');


}, 1000);

最佳答案

您需要使用 .each()。像这样的东西:

$('.countdown').each(function() {
var $this = $(this),
text = $this.text(),
targetDate = new Date(text).getTime();

setInterval(function() {
var currentDate = new Date().getTime();
var secondsLeft = (targetDate - currentDate) / 1000;

var days = parseInt(secondsLeft / 86400);
secondsLeft = secondsLeft % 86400;

var hours = parseInt(secondsLeft / 3600);
secondsLeft = secondsLeft % 3600;

var minutes = parseInt(secondsLeft / 60);
seconds = parseInt(secondsLeft % 60);

// afiseaza data rezultata
$this.html('<table cellspacing="0" border="0" cellpadding="0" width="328" align="center"><tr> <td width="82">'+days+'<span class="gray_text">d</span></td> <td width="82">'+hours+'<span class="gray_text">h</span></td> <td width="82">'+minutes+'<span class="gray_text">m</span></td> <td width="82">'+seconds+'<span class="gray_text">s</span></td> </tr></table>');
});
});

关于javascript - 如何用倒计时替换特定的div内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18625474/

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