jQuery.cookie应用操作

时间:2023-07-14 22:17:43
//1.插件框架:
/*
* name @键
* value @值
* options @选项,包括有效期 路径 域名等
*/
jQuery.cookie = function(name, value, options) {} var cookie_name = 'cookie_name'; //2.1、设置cookie,通过时间间隔,单位"天"
$.cookie(cookie_name, 'cookie值', { path: '/', expires: 1 }); //2.2、设置cookie,通过到期时间,如:二十四小时后失效
var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
$.cookie(cookie_name, 'cookie值', { path: '/', expires: date }); //2.3、设置cookie,通过时间间隔,并且要求域名有效
$.cookie(cookie_name, 'cookie值', {expires: 7, path: '/', domain: 'gzmsg.com', secure: true}); //3、获取cookie
var cookie_value = $.cookie(cookie_name);
if (typeof (cookie_name) != "undefined" || cookie_name != null) {
//doing code
}
//4.1、删除cookie,删除所有cookie_name的键
$.cookie(cookie_name, null); //4.2、删除cookie,删除对应options选项的cookie_name的键
$.cookie(cookie_name, null, path: '/', domain: 'gzmsg.com'); //5、jQuery.cookie源码
jQuery.cookie = function(n, v, o) {
if (typeof v != "undefined") {
o = o || {};
if (v === null) {
v = "";
o.expires = -1
}
var e = "";
if (o.expires && (typeof o.expires == "number" || o.expires.toUTCString)) {
var f;
if (typeof o.expires == "number") {
f = new Date();
f.setTime(f.getTime() + (o.expires * 24 * 60 * 60 * 1000))
} else {
f = n.expires
}
e = "; expires=" + f.toUTCString()
}
var l = o.path ? "; path=" + (o.path) : "";
var g = o.domain ? "; domain=" + (o.domain) : "";
var a = o.secure ? "; secure" : "";
document.cookie = [n, "=", encodeURIComponent(v), e, l, g, a].join("")
} else {
var d = null;
if (document.cookie && document.cookie != "") {
var k = document.cookie.split(";");
for (var h = 0; h < k.length; h++) {
var c = jQuery.trim(k[h]);
if (c.substring(0, n.length + 1) == (n + "=")) {
d = decodeURIComponent(c.substring(n.length + 1));
break
}
}
}
return d
}
}