函數封裝:
var Cookie = function(name, value, options) {
// 如果第二個參數存在
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
// 設置失效時間
options.expires = -1;
}
var expires = '';
// 如果存在事件參數項,並且類型為 number,或者具體的時間,那么分別設置事件
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 : '', // 設置路徑
domain = options.domain ? '; domain=' + options.domain : '', // 設置域
secure = options.secure ? '; secure' : ''; // 設置安全措施,為 true 則直接設置,否則為空
// 把所有字符串信息都存入數組,然后調用 join() 方法轉換為字符串,並寫入 Cookie 信息
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // 如果第二個參數不存在
var CookieValue = null;
if (document.cookie && document.cookie != '') {
var Cookie = document.cookie.split(';');
for (var i = 0; i < Cookies.length; i++) {
var Cookie = (Cookie[i] || "").replace( /^\s+|\s+$/g, "");
if (Cookie.substring(0, name.length + 1) == (name + '=')) {
CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
break;
}
}
}
return CookieValue;
}
};
寫入cookie信息:
// 簡單寫入一條 Cookie 信息
cookie("user", "baidu");
// 寫入一條 Cookie 信息,並且設置更多選項
cookie("user", "baidu", {
expires: 10, // 有效期為 10 天
path: "/", // 整個站點有效
domain: "www.baidu.com", // 有效域名
secure: true // 加密數據傳輸
});
讀取:
cookie("user");
刪除:
cookie("user", null);
