2016-09-25 91 views
-3

我是JavaScript新手。我正在尝试编写一个javascript倒计时函数,但当我将一个php变量传递给"var now=new Date("<?php echo $start;?>");"时,它不起作用。它的工作原理当我仅使用"var now=new Date();" 预先感谢您。这里是我的代码...javascript倒计时不能正常工作

<?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

基本java脚本运行在客户端,而php就像你知道它的一个服务器端,所以没办法,那javascript看到php,这就是为什么它不能正常工作,你可以通过传递php变量来解决这个问题到html(输入),隐藏类型,像这样http:// prntscr .com/cm5jy4 – Laith

+0

所以发生的是,您将PHP变量传递给html标记,现在javascript可以读取它们。 – Laith

+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