清除cookie稳妥做法就是设置cookie与清除cookie写法一致,cookie清除不了的问题,主要出现在设置与清除cookie并非一端操作的情况下,此时需要注意path、domain的设置必须保持一致,注意下文中注释//warning
处代码,如下:
/*Days默认输入number或string格式数字=day;s10、m10、h10、d10分别代表秒、分、小时、天*/
function setCookie(name, value, Days) {
var cookieString = name + '=' + escape(value),
checkTime, checkMark;
if (!isNaN(+Days)) {
checkTime = +Days
} else {
checkTime = Days.substr(1);
checkMark = Days.substr(0, 1)
} if (checkTime > 0) {
var setDate = new Date();
setDate.setTime(setDate.getTime() + checkstr(checkMark, checkTime));
cookieString = name + '=' + escape(value) + '; expires=' + setDate.toGMTString() + ';path=/;domain=' + location.hostname
}
document.cookie = cookieString
}
function getCookie(name) {
var strCookie = document.cookie,
arrCookie = strCookie.split(';');
for (var i = 0, len = arrCookie.length; i < len; i++) {
var Arr_keyvalue = arrCookie[i].split('=');
if (Arr_keyvalue[0].replace(/(^\s*)|(\s*$)/g, "") == name) {
return unescape(Arr_keyvalue[1])
}
}
return ''
}
function deleteCookie(name) {
var setDate = new Date();
setDate.setTime(setDate.getTime() - 10000);
var value = getCookie(name);
if (value) {
document.cookie = name + '=' + value + '; expires=' + setDate.toGMTString() + ';path=/;domain=' + location.hostname
}
}
function checkstr(mark, Time) {
if (!mark) {
return Time * 24 * 60 * 60 * 1000
} else {
switch (mark) {
case 's':
return Time * 1000;
break;
case 'm':
return Time * 60 * 1000;
break;
case 'h':
return Time * 60 * 60 * 1000;
break;
case 'd':
return Time * 24 * 60 * 60 * 1000;
break;
default:
return false;
break
}
}
}