jQuery将cookie从时间值更改为会话值

时间:2012-02-15 09:44:33

标签: jquery cookies session-cookies

我完全不了解饼干......

我在我的网站上使用了Slidedeck,并且他们提供了一个代码,使返回到带有幻灯片的页面的人能够显示上次查看的幻灯片,而不是返回到开头。

然而,它设置了一周 - 我想要做的是将其更改为基于会话,以便在浏览器关闭时,cookie不再有效。这个脚本有可能吗?

我已经读过,如果您将到期时间更改为0,它会使其基于会话 - 所以我更改了:

else {
      var expires = "0";
    }

但是我认为这不是因为它上面的if语句而有效。

// The default slide to start on is 0.
  var startingSlide = 0;
  // If we find a cookie with the name that we previously saved, use it.
  if(readCookie('slideDeckDemoCurrentSlide')){
    // This overrides the default value of 0 if we find a cookie.
    startingSlide = readCookie('slideDeckDemoCurrentSlide');
  }
  var myDeck = $('.slidedeck').slidedeck({
    autoPlay: false,
    cycle: true,
    slideTransition: 'slide',
    touch: false,
    hideSpines: true,
    start: startingSlide, // tell the Deck where to start
    complete: function(deck){
      // Here we will set a cookie for one week.
      // This cookie will store the deck.current value.
      //createCookie(name,value,days)
      createCookie('slideDeckDemoCurrentSlide',deck.current,7)
    }
  });




  function createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    }
    else {
      var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
  }

  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)===' '){ c = c.substring(1,c.length); }
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }

  function eraseCookie(name) {
    createCookie(name,"",-1);
  }  

2 个答案:

答案 0 :(得分:1)

会话Cookie和浏览器Cookie没有任何共同之处。特别是Javascript在CLIENT上执行,因此您只能访问浏览器cookie。您可以使用.unload()检测浏览器是否已关闭或页面是否已关闭,然后删除Cookie:

$(window).unload( function () { //delete cookie } );

答案 1 :(得分:1)

如果要创建会话cookie,请不要使用expires选项。 这来自“jquery cookie”的官方文档:

  

定义cookie的生命周期。值可以是数字   解释为创建时的天数或Date对象。如果   省略,cookie成为会话cookie。

如果设置expires:0,则表示根本不会保存cookie。

相关问题