操作:
$.cookie(‘the_cookie’); // 读取 cookie
$.cookie(‘the_cookie’, 'the_value’); // 存储 cookie
$.cookie(‘the_cookie’, 'the_value’, { expires: 7 }); // 存储一个带7天期限的 cookie
$.cookie(‘the_cookie’, '', { expires: -1 }); // 删除 cookie
$.cookie(‘the_cookie’, 'the_value’); // 存储 cookie
$.cookie(‘the_cookie’, 'the_value’, { expires: 7 }); // 存储一个带7天期限的 cookie
$.cookie(‘the_cookie’, '', { expires: -1 }); // 删除 cookie
1 jQuery.cookie = function(name, value, options) { 2 if (typeof value != 'undefined') { // name and value given, set cookie 3 options = options || {}; 4 if (value === null) { 5 value = ''; 6 options.expires = -1; 7 } 8 var expires = ''; 9 if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 10 var date; 11 if (typeof options.expires == 'number') { 12 date = new Date(); 13 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 14 } else { 15 date = options.expires; 16 } 17 expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE 18 } 19 var path = options.path ? '; path=' + options.path : ''; 20 var domain = options.domain ? '; domain=' + options.domain : ''; 21 var secure = options.secure ? '; secure' : ''; 22 document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 23 } else { // only name given, get cookie 24 var cookieValue = null; 25 if (document.cookie && document.cookie != '') { 26 var cookies = document.cookie.split(';'); 27 for (var i = 0; i < cookies.length; i++) { 28 var cookie = jQuery.trim(cookies[i]); 29 // Does this cookie string begin with the name we want? 30 if (cookie.substring(0, name.length + 1) == (name + '=')) { 31 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 32 break; 33 } 34 } 35 } 36 return cookieValue; 37 } 38 }; 39 40