通过该插件的学习使我对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);
时间: 2024-10-13 18:29:19