一.封装
jQuery.cookie = function (key, value, options) { // key and value given, set cookie... if (arguments.length > 1 && (value === null || typeof value !== "object")) { options = jQuery.extend({}, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(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('')); }
二.调用
//存cookie jQuery.cookie("username","admin",{ expires:7 }); jQuery.cookie("password","123456",{ expires:7 }); //取cookie var username = $.cookie("username");
expires:7设置过期时间为7天,-1为关闭浏览器后失效
三.备注
JQuery的版本为1.6.2。以上为个人笔记,可能不具备参考性。