我需要从数据库获取时间后开始倒计时。

例如: 您已预订酒店,20 分钟后即可付款。

我的问题出在哪里?

数据库:

updated_at = 2016-10-11 11:47:58

HTML(框架是laravel 5):

<input type="hidden" id="updated_at" value="{{ $reserve -> updated_at }}"> 
<div>Reservation closes in <span id="time"></span> minutes!</div> 

脚本:

function startTimer(duration, display) { 
    var updated_at = $('#updated_at').val(); 
    console.log(updated_at); 
    var start = Date.now(updated_at), 
            diff, 
            minutes, 
            seconds; 
    function timer() { 
        diff = duration - (((Date.now(updated_at) - start) / 1000) | 0); 
 
        minutes = (diff / 60) | 0; 
        seconds = (diff % 60) | 0; 
 
        minutes = minutes < 10 ? "0" + minutes : minutes; 
        seconds = seconds < 10 ? "0" + seconds : seconds; 
 
        display.textContent = minutes + ":" + seconds; 
 
        if (diff <= 0) { 
            start = Date.now(updated_at) + 1000; 
        } 
    }; 
    timer(); 
    setInterval(timer, 1000); 
} 
 
window.onload = function () { 
    var fiveMinutes = 60 * 20, 
            display = document.querySelector('#time'); 
    startTimer(fiveMinutes, display); 
}; 

请您参考如下方法:

没问题,只是你的显示代码是错误的。 “display”没有在timer函数中定义,仅在onload函数中定义,并且它不是全局的,因此上下文不会传递。您的浏览器控制台可能出现错误,尽管您没有提及。解决方法:

1)改变

var fiveMinutes = 60 * 20, 
display = document.querySelector('#time'); 

简单

    var fiveMinutes = 60 * 20; 

2)改变

display.textContent = minutes + ":" + seconds; 

$("#time").text(minutes + ":" + seconds); 

3)更改

startTimer(fiveMinutes, display); 

startTimer(fiveMinutes); 

4)改变

function startTimer(duration, display) { 

function startTimer(duration) { 

仅此而已。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!