来自php时间戳差异的JavaScript倒计时

时间:2012-03-13 15:10:24

标签: php javascript jquery timestamp countdown

我想倒计时时间是php的两次时间差,结果是时间戳。

{var $time = new \DateTime()}        

<div class="date" data-date="{= ($time2->getTimestamp() - $time->getTimestamp())*1000}">

在数据日期中,我有时间差[时间戳]。现在我想要倒计时了。我从HTML获取此信息到JS。

$(function() {        
    $(".date").each(function(){         
        time = $(this).data('date');        
        $.countdown($(this).children(".countdown"), time);
    });
}); 

代码无效。

jQuery.countdown = function(selector, datevalue) {

                    var amount = datevalue;

        // catch past dates
        if(amount < 0){
            $(selector).html("Done");
        }

        // date is in the future, calculate the diff
        else{
            days=0;hours=0;mins=0;secs=0;out="";

            amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

            days=Math.floor(amount/86400);//days
            amount=amount%86400;

            hours=Math.floor(amount/3600);//hours
            amount=amount%3600;

            mins=Math.floor(amount/60);//minutes
            amount=amount%60;

            secs=Math.floor(amount);//seconds

            //if(days != 0){out += days +" day"+((days!=1)?"s":"")+", ";}
                            //if(days == 0) {
                                if(days != 0 || hours != 0){out += ((hours<10)?"0":"") + hours +":";}
                                if(days != 0 || hours != 0 || mins != 0){out += ((mins<10)?"0":"") + mins +":";}
                                out += ((secs<10)?"0":"") + secs;
                                $(selector).html(out);
                            //}
            // run it all again
            setTimeout(function() {  
                $.countdown(selector, datevalue);
            }, 1000); 

        }

};

来自JS的时间是在正确的地方,但它没有倒计时。

1 个答案:

答案 0 :(得分:0)

答案很简单:你不要减少 datevalue 变量。因此对于所有迭代都是一样的

请看下面的示例,它可以正常工作

jQuery.countdown = function(selector, datevalue) {

    var amount = datevalue;

    // catch past dates
    if(amount < 0){
        $(selector).html("Done");
    }

    // date is in the future, calculate the diff
    else{
        datevalue--;
        $(selector).html(datevalue);
        setTimeout(function() {  
            $.countdown(selector, datevalue);
        }, 1000); 
    }
};

$.countdown('.date', 10);​​​