javascript倒计时计时器的Cookie问题

时间:2014-09-29 02:56:29

标签: javascript jquery cookies

我设置了一个jQuery插件> {3}从3天开始倒计时。

时间不应该在刷新时重新开始。当用户回来时,它应该在它停止的地方继续让我们说半天后。 3天后,它应该重新加载。

一切看起来都很正确。但它不起作用。数字显示为NaN。

如果“until:new Date(cookie)”更改为“+ 2d”,这是插件的标准,它可以正常工作。如果使用cookie将其更改为提前3天,则会失败。

任何人都知道什么是错的?

$(document).ready(function(){

if (!$.cookie('offerTimer')){
    var now = new Date(); 
    timer = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 3);
    $.cookie('offerTimer', timer.format("yyyy, mm, dd"), { expires: 7, path: '/' });
}

var cookie = $.cookie('offerTimer');

$('#until3d').countdown({until: new Date(cookie), format: 'HMS'});
});

1 个答案:

答案 0 :(得分:0)

您正在将计时器变量创建为Date对象。 Date对象上没有格式化方法,因此timer.format(" yyyy,mm,dd")将生成错误。

您只需要保存计时器变量。它将被转换为cookie中的字符串,并且您已经将代码转换为将该字符串转换为Date对象时再读取它。

所以这应该有效:

$(document).ready(function() {

  if (!$.cookie('offerTimer')) {
    var now = new Date();
    timer = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 3);
    $.cookie('offerTimer', timer, {
      expires: 7,
      path: '/'
    });
  }

  var cookie = $.cookie('offerTimer'), 
    theDate;

  if (new Date(cookie) > new Date()) {
    theDate = new Date(cookie);
  } else {
    // if the cookie date has passed, then set the time date to now (so hopefully it just stays at zero)
    theDate = new Date();
  }
  $('#until3d').countdown({
    until: theDate,
     format: 'HMS'
  }); 


});
相关问题