gpt4 book ai didi

php循环内的javascript倒计时器不工作

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:25 24 4
gpt4 key购买 nike

嗨,我正在尝试通过 JavaScript 添加多个倒数计时器,但不知怎么的,它不起作用,谁能告诉我我做错了什么,我是一只新蜜蜂。

下面是代码:

php while loop {

<script>
var timer;

var days= <?php echo $datediff ; ?>;

var compareDate = new Date();
compareDate.setDate(compareDate.getDate() + <?php echo $datediff ?> ); //just for this demo today + 7 days

timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();

if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);

hours %= 24;
minutes %= 60;
seconds %= 60;

$(".days") .text(days);
$(".hours").text(hours);
$(".minutes").text(minutes);
$(".seconds").text(seconds);
}
}
</script>
<div class="timer">
<span class="days"></span>days
<span class="hours"></span>hours
<span class="minutes"></span>minutes
<span class="seconds"></span>seconds
</div>

我无法让计时器工作,已将 id 更改为类。

最佳答案

如果我的想法正确,您需要在这里使用全局变量和局部变量,不要在每个循环中覆盖全局范围的值。

检查此代码,如果它以某种方式帮助您,请告诉我。

<?php
$datediffs = [7, 8, 9, 10]; //let's say this is the array of results from the database
?>
<html>
<head>
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<script>
var timer = []
var timestamp = new Date()

function timeBetweenDates(toDate, key) {
var now = new Date()
var difference = toDate.getTime() - now.getTime()

if ( difference <= 0 )
{
// Timer done
clearInterval( timer[key] );
}
else
{
var seconds = Math.floor( difference / 1000 )
var minutes = Math.floor( seconds / 60 )
var hours = Math.floor( minutes / 60 )
var days = Math.floor( hours / 24 )

hours %= 24
minutes %= 60
seconds %= 60

var $timer = $( '.timer-' + key )

$timer.find( '.days' ).text( days )
$timer.find( '.hours' ).text( hours )
$timer.find( '.minutes' ).text( minutes )
$timer.find( '.seconds' ).text( seconds )
}
}
</script>

<?php foreach ( $datediffs as $key => $datediff ) : ?>
<script>
timer.push( setInterval( function()
{
var compareDate = new Date()
compareDate.setTime( timestamp.getTime() )
compareDate.setDate( compareDate.getDate() + <?php echo $datediff ?> )
timeBetweenDates( compareDate, <?php echo $key; ?> )
}, 1000) )
</script>

<div class="timer-<?php echo $key; ?>">
<span class="days"></span> days
<span class="hours"></span> hours
<span class="minutes"></span> minutes
<span class="seconds"></span> seconds
</div>
<?php endforeach; ?>
</body>
</html>

关于php循环内的javascript倒计时器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356107/

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