我是javascript的新手。我正在尝试编写一个javascript倒计时函数,但是当我将一个php变量传递给"var now=new Date("<?php echo $start;?>");"
时它无效。当我仅使用"var now=new Date();"
时,它有效
先感谢您。这是我的代码......
<?php
$db = new mysqli("localhost", "root", "", "ajax");
$db -> set_charset("utf8");
$query="SELECT * FROM data WHERE id=2";
$data=$db->query($query);
while ($dt=$data->fetch_assoc()) {
$start=$dt['start_time'];
$end=$dt['end_time'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Countdown</title>
<style type="text/css">
body {
background: #f6f6f6;
}
.countdownContainer{
position: absolute;;
top: 50%;
left: 50%;
transform : translateX(-50%) translateY(-50%);
text-align: center;
background: #ddd;
border: 1px solid #999;
padding: 10px;
box-shadow: 0 0 5px 3px #ccc;
}
.info {
font-size: 80px;
}
</style>
</head>
<body>
<table class="countdownContainer">
<tr class="info">
<td colspan="4">c Countdown c</td>
</tr>
<tr class="info">
<td id="days">120</td>
<td id="hours">4</td>
<td id="minutes">12</td>
<td id="seconds">22</td>
</tr>
<tr>
<td>Days</td>
<td>Hours</td>
<td>Minutes</td>
<td>Seconds</td>
<td id="start_date"><?php echo $start;?></td>
<td id="php_date_time"></td>
</tr>
</table>
<script type="text/javascript">
function countdown(){
var now = new Date("<?php echo $start;?>");
var eventDate = new Date("<?php echo $end;?>");
// alert(now);
var currentTiime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTiime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
setTimeout(countdown, 1000);
}
countdown();
</script>
答案 0 :(得分:0)
您的PHP仅在页面刷新时更新,因此每次调用倒计时函数时它都具有完全相同的值:
function countdown(){
var now = new Date("<?php echo $start;?>"); <--- this never changes
var eventDate = new Date("<?php echo $end;?>"); <--- this never changes
var currentTiime = now.getTime(); <--- this result is always the same
var eventTime = eventDate.getTime(); <--- so is this one
var remTime = eventTime - currentTiime; < --- obviously this one too