码迷,mamicode.com
首页 > Web开发 > 详细

JS - Cookie: getCookie, setCookie

时间:2015-11-10 13:44:13      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

JS function for Cookie

如果cookie未设置,判断时与‘’比较;

1 function setCookie(cname, cvalue, exdays) {
2     var d = new Date();
3     d.setTime(d.getTime() + (exdays*24*60*60*1000));
4     var expires = "expires="+d.toUTCString();
5     document.cookie = cname + "=" + cvalue + "; " + expires;
6 }
7     
 1 function getCookie(cname) {
 2     var name = cname + "=";
 3     var ca = document.cookie.split(‘;‘);
 4     for(var i=0; i<ca.length; i++) {
 5         var c = ca[i];
 6         while (c.charAt(0)==‘ ‘) c = c.substring(1);
 7         if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
 8     }
 9     return "";
10 }

当使用jQuery cookie时,

$.cookie(‘the_cookie‘); // 读取 cookie 
$.cookie(‘the_cookie‘, ‘the_value‘); // 存储 cookie 
$.cookie(‘the_cookie‘, ‘the_value‘, { expires: 7 }); // 存储一个带7天期限的 cookie 
$.cookie(‘the_cookie‘, ‘‘, { expires: -1 }); // 删除 cookie

 如果cookie未设置,判断时与undefined比较;

JS - Cookie: getCookie, setCookie

标签:

原文地址:http://www.cnblogs.com/tx8899/p/4952430.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!