jQuery操作Cookie
1 //关于cookie的path设置需要注意,如果不设置path:'/'的话,path则会根据目录自动设置[如:http://www.xxx.com/user/,path会被设置为 '/user'] 2 $.extend({ 3 4 /** 5 1. 设置cookie的值,把name变量的值设为value 6 example $.cookie("name", "value"); 7 2.新建一个cookie 包括有效期 路径 域名等 8 example $.cookie("name", "value", {expires: 7, path: "/", domain: "jquery.com", secure: true}); 9 3.新建cookie 10 example $.cookie("name", "value"); 11 4.删除一个cookie 12 example $.cookie("name", null); 13 5.取一个cookie(name)值给myvar 14 var account= $.cookie('name'); 15 **/ 16 cookieHelper: function(name, value, options) { 17 if (typeof value != 'undefined') { // name and value given, set cookie 18 options = options || {}; 19 if (value === null) { 20 value = ''; 21 options.expires = -1; 22 } 23 var expires = ''; 24 if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 25 var date; 26 if (typeof options.expires == 'number') { 27 date = new Date(); 28 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 29 } else { 30 date = options.expires; 31 } 32 expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE 33 } 34 var path = options.path ? '; path=' + options.path : ''; 35 var domain = options.domain ? '; domain=' + options.domain : ''; 36 var secure = options.secure ? '; secure' : ''; 37 document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 38 } else { // only name given, get cookie 39 var cookieValue = null; 40 if (document.cookie && document.cookie != '') { 41 var cookies = document.cookie.split(';'); 42 for (var i = 0; i < cookies.length; i++) { 43 var cookie = jQuery.trim(cookies[i]); 44 // Does this cookie string begin with the name we want? 45 if (cookie.substring(0, name.length + 1) == (name + '=')) { 46 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 47 break; 48 } 49 } 50 } 51 return cookieValue; 52 } 53 } 54 });
本文来自:http://www.cnblogs.com/diulela/archive/2011/12/28/2304413.html