cookie存储涉及到几个参数,当其中的参数不一样的时候,可能导致,cookie的key可以相同。
常用的:
- name
- Domain
- Path
- secure
cookie: function(name, value, options) {
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
value = '';
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();
}
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 {
var cookieValue = null;
if (document.cookie) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
},
removeCookie: function(cookieName) {
var cookies = document.cookie.split(";");//将所有cookie键值对通过分号分割为数组
//循环遍历所有cookie键值对
for (var i = 0; i < cookies.length; i++) {
//有些cookie键值对前面会莫名其妙产生一个空格,将空格去掉
if (cookies[i].indexOf(" ") == 0) {
cookies[i] = cookies[i].substring(1);
}
//比较每个cookie的名称,找到要删除的那个cookie键值对
var cookie_name = cookies[i].split("=")[0];
if (cookie_name == cookieName) {
var exp = new Date();
exp.setTime(exp.getTime() - 6000 * 1000);
document.cookie = cookies[i] + ";path=/;domain=.imihuan.com;expires=" + exp.toUTCString();
break;
}
}
},