jQuery的cookie插件
02 |
jQuery.cookie = function (name, value, options) {
|
03 |
if ( typeof value != 'undefined' ) {
|
04 |
options = options || {};
|
07 |
options = $.extend({}, options);
|
11 |
if (options.expires && ( typeof options.expires == 'number' || options.expires.toUTCString)) {
|
13 |
if ( typeof options.expires == 'number' ) {
|
15 |
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
|
17 |
date = options.expires;
|
19 |
expires = '; expires=' + date.toUTCString();
|
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( '' );
|
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));
|
具体用法如下:
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');