Js操作Cookie的代碼,下邊的代碼內有詳細注釋,這里就不再多說了,直接上代碼:
/*
*設置與獲取Cookie
*/
var Cookie = {}
//寫入Cookie,key為鍵,value是值
//duration過期時間(天為單位,默認1天)
Cookie.write = function (key, value, duration)
{
Cookie.remove(key);
var d = new Date();
if (duration <= 0)
duration = 1;
d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * duration);
document.cookie = key + "=" + encodeURI(value) + "; expires=" + d.toGMTString() + ";path=/";
};
//移除Cookie,key為鍵
Cookie.remove = function (key)
{
var d = new Date();
if (Cookie.read(key) != "")
{
d.setTime(d.getTime() - (86400 * 1000 * 1));
document.cookie = key + "=;expires=" + d.toGMTString();
}
};
//更多教程:Veryhuo.Com
//讀取Cookie,key是鍵
//不存在返回空字符串""
Cookie.read = function (key)
{
var arr = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
if (arr != null)
return decodeURIComponent(arr[2]);
return "";
};