【JavaScript代码实现四】获取和设置 cookie
1 // 创建cookie 2 function setCookie(name, value, expires, path, domain, secure) { 3 var cookieText = encodeURIComponent(name) + '=' +encodeURIComponent(value); 4 if (expires instanceof Date) { 5 cookieText += '; expires=' + expires; 6 } 7 if (path) { 8 cookieText += '; expires=' + expires; 9 } 10 if (domain) { 11 cookieText += '; domain=' + domain; 12 } 13 if (secure) { 14 cookieText += '; secure'; 15 } 16 document.cookie = cookieText; 17 } 18 // 获取cookie 19 function getCookie(name) { 20 var cookieName = encodeURIComponent(name) + '='; 21 var cookieStart = document.cookie.indexOf(cookieName); 22 var cookieValue = null; 23 if (cookieStart > -1) { 24 var cookieEnd = document.cookie.indexOf(';', cookieStart); 25 if (cookieEnd == -1) { 26 cookieEnd = document.cookie.length; 27 } 28 cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd)); 29 } 30 return cookieValue; 31 } 32 // 删除cookie 33 function unsetCookie(name) { 34 document.cookie = name + "= ; expires=" + new Date(0); 35 }