其实也没太大难度,主要注意设置cookie的时候需要统一path,因为现在很多pathinfo模式的url,会导致path不统一,你在 www.domain.com/foo 路径下设置的cookie在www.domain.com/bar下可能会读取不到,因为path可能不同,默认 / 最好
1//增加或者更新cookie 2function setCookie(c_name, value, expiredays, path) { 3 var expiredays = arguments[2] ? arguments[2] : 1; 4 var path = arguments[3] ? arguments[3] : '/'; 5 console.log(expiredays, path); 6 var exdate = new Date(); 7 exdate.setDate(exdate.getDate() + expiredays * 24 * 60 * 60 * 1000); 8 document.cookie = c_name + "=" + escape(value) + 9 ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + ";path=" + path); 10} 11 12//获取cookie 13function getCookie(c_name) { 14 if (document.cookie.length > 0) { 15 c_start = document.cookie.indexOf(c_name + "="); 16 if (c_start != -1) { 17 c_start = c_start + c_name.length + 1; 18 c_end = document.cookie.indexOf(";", c_start); 19 if (c_end == -1) c_end = document.cookie.length 20 return unescape(document.cookie.substring(c_start, c_end)); 21 } 22 } 23 return ""; 24} 25 26//删除cookie 27function delCookie(c_name, path) { 28 var path = arguments[1] ? arguments[1] : '/'; 29 var exp = new Date(); 30 exp.setTime(exp.getTime() - 1); 31 var cval = getCookie(c_name); 32 if (cval != null) document.cookie = c_name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=" + path; 33} 34 35setCookie("name", "sallency"); 36 37getCookie("name"); 38 39delCookie("name");