jQuery的Cookie操作插件

jQuery的cookie插件

01 // jQuery.cookie.js
02 jQuery.cookie = function(name, value, options) {
03     if (typeof value != 'undefined') {
04         options = options || {};
05         if (value === null) {
06             value = '';
07             options = $.extend({}, options);
08             options.expires = -1;
09         }
10         var expires = '';
11         if (options.expires && (typeof options.expires == 'number'|| options.expires.toUTCString)) {
12             var date;
13             if (typeof options.expires == 'number') {
14                 date = new Date();
15                 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
16             else {
17                 date = options.expires;
18             }
19             expires = '; expires=' + date.toUTCString();
20         }
21         var path = options.path ? '; path=' + (options.path) : '';
22         var domain = options.domain ? '; domain=' + (options.domain) : '';
23         var secure = options.secure ? '; secure' '';
24         document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
25     else {
26         var cookieValue = null;
27         if (document.cookie && document.cookie != '') {
28             var cookies = document.cookie.split(';');
29             for (var i = 0; i < cookies.length; i++) {
30                 var cookie = jQuery.trim(cookies[i]);
31                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
32                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
33                     break;
34                 }
35             }
36         }
37         return cookieValue;
38     }
39 };

具体用法如下:

1、设置cookie的值,比如我们要设置变量名为userid对应值为123的cookie,代码如下:

$.cookie('userid','123');

2、新建一个cookie,并设置cookie的有效期 路径 域名等,代码如下:

$.cookie('userid, '123', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); 
注意:如果去掉后面{}的参数,新建后将以默认设置生效。

3、删除cookie,即把对应cookie值置为null,代码如下:

$.cookie('userid', null);

4、读取cookie,如读取变量名为userid的cookie值,代码如下: 
var uId= $.cookie('userid');

上一篇:读ios开发有感——建立APP开发体系


下一篇:STM32管教复用与重映射关系