作者:tianziqizhi | 来源:互联网 | 2018-06-19 10:46
代码:
代码如下:
jQuery.COOKIE = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set COOKIE
optiOns= options || {};
if (value === null) {
value = '';
optiOns= $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' (options.path) : '';
var domain = options.domain ? '; domain=' (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.COOKIE = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get COOKIE
var COOKIEValue = null;
if (document.COOKIE && document.COOKIE != '') {
var COOKIEs = document.COOKIE.split(';');
for (var i = 0; i var COOKIE = jQuery.trim(COOKIEs[i]);
// Does this COOKIE string begin with the name we want?
if (COOKIE.substring(0, name.length 1) == (name '=')) {
COOKIEValue = decodeURIComponent(COOKIE.substring(name.length 1));
break;
}
}
}
return COOKIEValue;
}
};
使用方法 jQuery操作COOKIE的插件,大概的使用方法如下
$.COOKIE('the_COOKIE'); //读取COOKIE值
$.COOKIE('the_COOKIE', 'the_value'); //设置COOKIE的值
$.COOKIE('the_COOKIE', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});//新建一个COOKIE 包括有效期 路径 域名等
$.COOKIE('the_COOKIE', 'the_value'); //新建COOKIE
$.COOKIE('the_COOKIE', null); //删除一个COOKIE
设置一个名称为blog,值为css9.net的COOKIE:
$.COOKIE("blog", "css9.net");
设置一个名称为blog,值为css9.net的COOKIE,同时设置过期时间(expires属性)为7天:
$.COOKIE("blog", "css9.net", { expires: 7 });
设置一个名称为blog,值为css9.net的COOKIE,设置过期时间(expires属性)为7天,同时设置COOKIE的path属性为”/admin”
$.COOKIE("blog", "css9.net", { path: '/admin', expires: 7 });
读取COOKIE:
读取名称为blog的COOKIE值:
alert( $.COOKIE("blog") );
删除COOKIE:
$.COOKIE("example", null);