1. 程式人生 > >cookie 的相關操作

cookie 的相關操作

// 設定cookie
function setCookie(name, value) {
var curDate = new Date();
//當前時間戳
var curTamp = curDate.getTime();
//當日凌晨的時間戳,減去一毫秒是為了防止後續得到的時間不會達到00:00:00的狀態
var curWeeHours = new Date(curDate.toLocaleDateString()).getTime() - 1;
//當日已經過去的時間(毫秒)
var passedTamp = curTamp - curWeeHours;
//當日剩餘時間
var leftTamp = 24 * 60 * 60 * 1000 - passedTamp;
var leftTime = new Date();
leftTime.setTime(leftTamp + curTamp);
document.cookie = name + "=" + escape(value) + ";expires=" + leftTime.toGMTString();
}

//刪除cookie
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

// 取出cookie
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}