使用jquery cookie记住页面刷新时切换的div

时间:2013-08-18 19:06:45

标签: jquery cookies toggle

如何使用jquery设置cookie以记住切换哪个div并在刷新页面时保持切换?

我已经尝试了很多解决方案并且几乎已经弄明白了,但是在设置和检索cookie时我遇到了困难。

My HTML:
<a href="javascript:showonlyone('newboxes2');" >Login</a>
<a href="javascript:showonlyone('newboxes3');" >Register</a>

<div class="newboxes" id="newboxes1" style="display: block">
   default text to be shown when no cookies are set
</div>

<div class="newboxes" id="newboxes2" style="display: none">
login form
</div>

<div class="newboxes" id="newboxes3" style="display: none"> 
register form       
</div>  

我的剧本:               

/************jQuery Cookie**************/
;(function(g){g.cookie=function(h,b,a){if(1<arguments.length&&(!/Object/.test(Object.prototype.toString.call(b))||null===b||void 0===b)){a=g.extend({},a);
if(null===b||void 0===b)a.expires=-1;
if("number"===typeof a.expires){var d=a.expires,c=a.expires=new Date;
c.setDate(c.getDate()+d)}b=""+b;
return document.cookie=[encodeURIComponent(h),"=",a.raw?b:encodeURIComponent(b),a.expires?";
expires="+a.expires.toUTCString():"",a.path?";
path="+a.path:"",a.domain?";
domain="+a.domain:"",a.secure?";
secure":
""].join("")}for(var a=b||{},d=a.raw?function(a){return a}:decodeURIComponent,c=document.cookie.split("; "),e=0,f;f=c[e]&&c[e].split("=");
e++)if(d(f[0])===h)return d(f[1]||"");
return null}})(jQuery);

if ($.cookie('showDiv') == 'newboxes2'){
 newboxes2.show();
}

if ($.cookie('showDiv') == 'newboxes3'){
 newboxes3.show();
}

function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
    if ($(this).attr("id") == thechosenone) {
         $(this).show(200);
         $.cookie('showDiv', thechosenone);
    }
    else {
         $(this).hide(600);
    }
});
}

如果cookie代码格式不正确,那么这里有一个工作示例:http://jsfiddle.net/CQFJ4/但是那个小提琴不能满足我的需要,我只是借用了cookie代码。

我遇到的地方是使用$(this)在每个循环中设置Cookie 然后在刷新页面时调用该cookie 感谢您的帮助,我非常感谢!

1 个答案:

答案 0 :(得分:1)

如果将this放在字符串中,它将不会被解释为标识符,它只是那四个字符。您需要将元素中的id连接到字符串中,因此这适用于您当前的代码:

$.cookie($(this).attr('id') + '.showDiv', 'visible');

但是,每个请求中的每个请求都会在服务器和浏览器之间向前发送每个Cookie值,并且域允许的Cookie限制为几千字节,因此您应该保留饼干尽可能小。使用单个cookie并将可见元素的标识放在值中:

$.cookie('showDiv', thechosenone);

然后在显示元素时检查值:

if ($.cookie('showDiv') == 'newboxes2'){
  newboxes2.show();
}