前段时间做项目的时候要使用js操作cookie,jquery也有相应的插件,不过还是觉得纯生的js比较好,毕竟不依赖jq.
1 //获得coolie 的值 2 function cookie(name) { 3 var cookieArray = document.cookie.split("; "); //得到分割的cookie名值对 4 var cookie = new Object(); 5 6 for (var i = 0; i < cookieArray.length; i++) { 7 8 var arr = cookieArray[i].split("="); //将名和值分开 9 10 //如果是指定的cookie,则返回它的值 11 if (arr[0] == name) { 12 return unescape(arr[1]); 13 } 14 } 15 16 return ""; 17 } 18 19 function delCookie(name)//删除cookie 20 { 21 document.cookie = name + "=;expires=" + (new Date(0)).toGMTString(); 22 } 23 24 function getCookie(objName) {//获取指定名称的cookie的值 25 26 var arrStr = document.cookie.split("; "); 27 28 for (var i = 0; i < arrStr.length; i++) { 29 30 var temp = arrStr[i].split("="); 31 32 if (temp[0] == objName) return unescape(temp[1]); 33 34 } 35 } 36 37 function addCookie(objName, objValue, objHours) { //添加cookie 38 39 var str = objName + "=" + escape(objValue); 40 41 if (objHours > 0) { //为时不设定过期时间,浏览器关闭时cookie自动消失 42 43 var date = new Date(); 44 45 var ms = objHours * 3600 * 1000; 46 47 date.setTime(date.getTime() + ms); 48 49 str += "; expires=" + date.toGMTString(); 50 51 } 52 53 document.cookie = str; 54 } 55 56 function SetCookie(name, value)//两个参数,一个是cookie的名子,一个是值 57 { 58 var Days = 30; //此 cookie 将被保存 30 天 59 var exp = new Date(); //new Date("December 31, 9998"); 60 exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); 61 62 document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); 63 } 64 65 function getCookie(name)//取cookies函数 66 { 67 var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); 68 69 if (arr != null) { 70 return unescape(arr[2]); 71 } 72 73 return null; 74 } 75 76 function delCookie(name)//删除cookie 77 { 78 var exp = new Date(); 79 exp.setTime(exp.getTime() - 1); 80 var cval = getCookie(name); 81 82 if (cval != null) { 83 document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); 84 } 85 }