我需要一些有关JavaScript代码的帮助,我尝试获取在同一页面上适用于多个倒数计时器的代码。我尝试了下面的代码,但没有成功。
<div class="expirydiv">Jan 02,2019</div>
<div class="expirydiv">jun 15,2019</div>
<script>
// Set the date we're counting down to
var ps = document.querySelectorAll("div.expirydiv");
var countDownDate = new Date(ps).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 classname="expirydiv"
for(var i=0; i<ps.length; i++){
ps[i].innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
ps[i].innerHTML = "EXPIRED";
}
}
}, 1000);
</script>
以上代码的结果如下所示:
NaNd NaNh NaNm NaNs
NaNd NaNh NaNm NaNs
此代码有什么问题,我认为查询选择器无法选择div.expirydiv作为日期。
答案 0 :(得分:0)
将var countDownDate = new Date(ps).getTime();
更改为var countDownDate = new Date(ps[0].innerHTML).getTime();
答案 1 :(得分:0)
您正在使用多个倒数计时,因此您需要遍历它们并设置计时器。
var ps = document.querySelectorAll("div.expirydiv");
ps.forEach(function(timer){
var countDownDate = new Date(timer.innerText).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
timer.innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
timer.innerHTML = "EXPIRED";
}
}, 1000);
});
<div class="expirydiv">Dec 02,2019</div>
<div class="expirydiv">Dec 15,2019</div>