0

我有一个电子商务网站,购物篮时间最长为 20 分钟。我在 JS 中编写了一个简单的计数器来显示剩余时间,如下所示:

 function basketCounter() {
    var minutes = Math.floor(count / 60);
    var sec = count - minutes * 60;
    if (sec < 10) {
        sec = '0' + sec;
    }
    console.log("hello");
    $(".temps_restant").html("reste: " + minutes + " : " + sec );
    $("#tunnel_panier_temps").html("" + minutes);
    if (count == 0) {
        window.location = '{{serverRequestUri}}flush_panier/1/';
    }
    count--;
}

在体内:

var count = {{panierTmp.lifetime - now}};
$(document).bind('pageinit', function() {
    $("img.lazy").unveil();
    if (count > 0) {
        setInterval('basketCounter()', 1000);
    }
});

当我在没有 ajax 的网站上导航时,它工作正常。但是当我试图在 JQM 中导航 ajax 时,计数器每次都重新执行并加速,2 秒乘 2 秒,如果我返回两次,它将是 3 秒乘 3 秒。

我找不到任何解决方案..

4

2 回答 2

0

您的 pageinit 错误,它应该只执行一次:

var count = {{panierTmp.lifetime - now}};
var interval=null;
$(document).bind('pageinit', function() {
    $("img.lazy").unveil();
    if (count > 0 && !interval) {
        interval=setInterval('basketCounter()', 1000);
    }
});

如果没有这个检查,每个 pageinit 事件都会添加另一个调用 basketCounter 的间隔。

您还可以检查数据是否存在,而不是设置变量。

if(!$(document).hasData('basketCounter')){
    $(document).data('basketCounter',{{panierTmp.lifetime - now}});
}
于 2013-08-20T14:51:00.653 回答
0

您可以尝试以下方法:

1)尝试删除任何隐藏页面

<head>
    document.on('pagehide', function(e) {
       $(e.target).remove();
    });
</head>

2) 解除绑定页面事件。

$(document).off('pageinit').on('pageinit', ....
于 2013-08-20T20:34:00.657 回答