在網頁前端開發中,讀取或設定 cookie 是很常見的需求。若用原生 JavaScript 硬寫,常會踩到跨瀏覽器相容性的坑。這裡介紹一個實用的 jQuery cookie 插件,幫你把這些麻煩都收攏好。
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options);
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 && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
1. 設定 cookie 值——例如建立名為 userid、值為 123 的 cookie:
$.cookie('userid','123');
2. 建立並設定有效期、路徑、網域:
$.cookie('userid', '123', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
注意:若省略後方的 {} 參數,新建的 cookie 會以預設值生效。
3. 刪除 cookie——把值設為 null 即可:
$.cookie('userid', null);
4. 讀取 cookie:
var uId = $.cookie('userid');
用 jQuery 操作 cookie 是不是清爽多了?你不必自己刻一堆繁瑣的 js,也不用煩惱各家瀏覽器的差異,設定、讀取、刪除都只是呼叫同一個方法、換個參數而已。對於需要記住登入狀態、使用者偏好等場景,這個小插件能省下不少功夫。