用JavaScript创建、获取、删除Cookie的例子
1、创建cookie
1 function setCookies(cName,cValue,exTimes){ 2 var d = new Date(); 3 d.setTime(d.getTime()+exTimes*24*60*60*1000); 4 var expires = "expires"+d.toUTCString(); 5 document.cookie=cName+"="+cValue+";"+expires; 6 }
参数说明:
1、cName :cookie的键
2、cValue:cookie的值
3、exTimes:cookie的过期时间。从当前时间开始,过exTimes天之后过期
2、获取cookie
1 function getCookie(cName){ 2 var name = cName; 3 var cookies = document.cookie.split(";"); 4 for(var i=0;i<cookies.length;i++){ 5 var cookie = cookies[i]; 6 while(cookie.charAt(0)==" ") cookie=cookie.substring(1); 7 if(cookie.indexOf(name)!=-1){ 8 return cookie.substring(name.length+1,cookie.length); 9 }else{ 10 return ""; 11 } 12 } 13 14 }
下面解释这句:
while(cookie.charAt(0)==" ") cookie=cookie.substring(1);
先来看看获取的cookie的样式:
可以看到第二和第三个cookie值得第一个位置的字符为" ",所以当cookie.charAt(0)==" "时获取的cookie应该是从第二个字符到结尾的字符串
3、删除cookie
1 function clearCookie(cName){ 2 setCookies(cName,"",-1); 3 }
-1代表关闭浏览器时失效