1 var CookieUtils = { 2 get: function (name) { 3 var cookieName = encodeURIComponent(name) + ‘=‘, 4 cookieStart = document.cookie.indexOf(cookieName), 5 cookieValue = null; 6 if (cookieStart > -1) { 7 var cookieEnd = document.cookie.indexOf(‘;‘, cookieStart); 8 if (cookieEnd == -1) { 9 cookieEnd = document.cookie.length; 10 } 11 cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd)); 12 } 13 return cookieValue; 14 }, 15 set: function (name, value, expires, path, domain, secure) { 16 var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value); 17 if (expires instanceof Date) { 18 cookieText += "; expried=" + expires.toGMTString(); 19 } 20 if (path) { 21 cookieText += "; path=" + path; 22 } 23 if (domain) { 24 cookieText += "; domain=" + domain; 25 } 26 if (secure) { 27 cookieText += "; secure"; 28 } 29 document.cookie = cookieText; 30 }, 31 unset: function (name, path, domain, secure) { 32 this.set(name, "", new Date(0), path, domain, secure); 33 } 34 }
这样即可以调用CookieUtils.get/set/unset方法进行Cookie操作。
项目完成后会对本方法进行进一步完善。
参考自《Javascript高级程序设计》
时间: 2024-11-06 14:33:15