js入门教程:js cookie 的时间设置与删除cookie,我们经常会用到js 来写cookie,设置cookie的 时间,j在过期后 删除cookie值
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> js cookie教程</title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="中国web第一站">
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
var Cookie=new Object();
Cookie.setCookie=function(name,value,option){
//用于存储赋值给document.cookie的cookie格式字符串
var str=name+"="+escape(value);
if(option){
//如果设置了过期时间
if(option.expireDays){
var date=new Date();
var ms=option.expireDays*24*3600*1000;
date.setTime(date.getTime()+ms);
str+="; expires="+date.toGMTString();
}
if(option.path)str+="; path="+path; //设置访问路径
if(option.domain)str+="; domain"+domain; //设置访问主机
if(option.secure)str+="; true"; //设置安全性
}
document.cookie=str;
}
Cookie.getCookie=function(name){
var cookieArray=document.cookie.split("; "); //得到分割的cookie名值对
var cookie=new Object();
for(var i=0;i<cookieArray.length;i++){
var arr=cookieArray[i].split("="); //将名和值分开
if(arr[0]==name)return unescape(arr[1]); //如果是指定的cookie,则返回它的值
}
return "";
}
Cookie.deleteCookie=function(name){
this.setCookie(name,"",{expireDays:-1}); //将过期时间设置为过去来删除一个cookie
}
Cookie.setCookie("user","jack");
alert(Cookie.getCookie("user"));
Cookie.deleteCookie("user");
alert(Cookie.getCookie("user"));
//-->
</script>
</body>
</html>