1. 程式人生 > >【jQuery】cookie插件

【jQuery】cookie插件

tostring options pat ret path spa prototype 直觀 emp

通過該插件的學習使我對cookie、Date()、getDate()、setDate()、toUTCString()有了更直觀的了解,具體分析見註釋:

function(key, value, options),調用該插件需要傳入三個參數

如:

var COOKIE_NAME = ‘test_cookie‘;
var ADDITIONAL_COOKIE_NAME = ‘additional‘;
$(‘a‘).eq(0).click(function() { // 用天數設置 cookie
$.cookie(COOKIE_NAME, ‘test‘, { path: ‘/‘, expires: 10 });
return false;
});

/*!
 * jQuery Cookie Plugin
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($) {
    $.cookie = function(key, value, options) {

        
// key and at least value given, set cookie... if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) { options = $.extend({}, options); if (value === null || value === undefined) { options.expires
= -1; } if (typeof options.expires === ‘number‘) { var days = options.expires, t = options.expires = new Date();//創建一個Date對象,不傳參數的情況下,該對象自動獲取當前日期和時間 t.setDate(t.getDate() + days);//getDate(),返回日期月份中的天數(1到31) //setDate(),設置日期月份中的天數,最終options.expires指向這個期限 } value = String(value); return (document.cookie = [//只設置了cookie的值和有效日期,其余為空,使用Date對象的toUTCString()格式化Date對象 encodeURIComponent(key), ‘=‘, options.raw ? value : encodeURIComponent(value), options.expires ? ‘; expires=‘ + options.expires.toUTCString() : ‘‘, // use expires attribute, max-age is not supported by IE options.path ? ‘; path=‘ + options.path : ‘‘, options.domain ? ‘; domain=‘ + options.domain : ‘‘, options.secure ? ‘; secure‘ : ‘‘ ].join(‘‘)); } // key and possibly options given, get cookie... options = value || {}; var decode = options.raw ? function(s) { return s; } : decodeURIComponent; var pairs = document.cookie.split(‘; ‘); for (var i = 0, pair; pair = pairs[i] && pairs[i].split(‘=‘); i++) { if (decode(pair[0]) === key) return decode(pair[1] || ‘‘); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined } //判斷COOKIE_NAME是否相同,返回pair[1],即cookie值,遇return直接結束 return null; }; })(jQuery);

【jQuery】cookie插件