1 //1. 获得指定名称为ObjName的Cookie的值 2 function getCookie(ObjName){ 3 var arrStr = document.cookie.split("; "); //各个Cookie之间以;分隔 4 for(var i=0;i<arrStr.length;i++){ 5 var temp = arrStr[i].split("="); //Cookie名和Cookie值之间以 = 分隔 6 if(temp[0] == ObjName) 7 return unescape(temp[1]); 8 } 9 return ""; 10 } 11 12 //2.添加Cookie值到浏览器内置documnet.cookie对象中 13 function addCookie(objName,objValue,objHours){ 14 var str = objName + "=" + escape(objValue); 15 if(objHours > 0){ //如果不设定过期时间(即当objHours<=0时),浏览器关闭时cookie将会被自动删除 16 var date = new Date(); 17 var ms = objHours*3600*1000; 18 date.setTime(date.getTime() + ms); 19 str += "; expires=" + date.toGMTString(); 20 } 21 document.cookie = str; 22 } 23 24 //3. 设置名为objName的Cookie的值,并且设置过期时间为30天 25 function SetCookie(objName,objValue){ 26 var Days = 30; //表示此cookie将被保存30天 27 var exp = new Date(); 28 exp.setTime(exp.getTime() + Days*24*60*60*1000); 29 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 30 } 31 32 //4. 删除名字为objName的Cookie 33 function delCookie(objName){ 34 var exp = new Date(); 35 exp.setTime(exp.getTime()-1); 36 var value=getCookie(objName); 37 if(value!=null) { 38 document.cookie= name + "="+value+";expires="+exp.toGMTString(); 39 } 40 }