接上篇文章接着写,上次讲到存取数据,现在主要介绍删除cookie的操作。
前面说到的cookie设置,在你关闭浏览器之后,就会自动清掉了,实际上那些cookie设置是保存在内存中的,如果这样就能满足用户需求,那我们通常是不用cookie的。直接保存了一个变量里就好了。
为了让用户下次打开浏览器还能看到之前的cookie,我们需要把cookie保存在硬盘上。这时候我们需要设置一个属性,过期时间。
document.cookie="userName=lzl; expires=GMT_String";
其中GMT_String是以GMT格式表示的时间字符串,这条语句就是将userName这个cookie设置为GMT_String表示的过期时间,超过这个时间,cookie将消失,不可访问。
比如设置一个cookie,7天内可访问。代码如下
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie test</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script>
function setCookie() {
<!--
//获取当前时间
var date=new Date();
var expireDays=7;
//将date设置为7天以后的时间
date.setTime(date.getTime()+expireDays*24*3600*1000);
//将设置为7天后过期
document.cookie = "userName=lzl; expires=" + date.toGMTString();
//-->
}
function showCookie() {
if (document.cookie)
{
alert(document.cookie)
}
else{alert("document.cookie 不存在");}
}
</script>
</head>
<body>
<input type="button" οnclick="setCookie()" value="设置cookie"/>
<input type="button" οnclick="showCookie()"value="显示cookie"/>
</body>
</html>
上面的代码,在设置cookie后7天之内,点击显示cookie,都能弹出之前设置的值。
删除已经存在的cookie也是利用了时间,不过把过期时间设置为过去的某一个时间,cookie就会自动清掉相应的设置了。代码如下
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie test</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script>
function setCookie() {
<!--
//获取当前时间
var date=new Date();
var expireDays=7;
//将date设置为7天以后的时间
date.setTime(date.getTime()+expireDays*24*3600*1000);
//设置为7天后过期
document.cookie = "userName=lzl; expires=" + date.toGMTString();
//-->
}
function delCookie() {
var date = new Date();
date.setTime(date.getTime()-10000);
//设置过期时间为已经过去的时间点
document.cookie = "userName=lzl; expires=" + date.toGMTString();
}
function showCookie() {
if (document.cookie)
{
alert(document.cookie)
}
else{alert("document.cookie 不存在");}
}
</script>
</head>
<body>
<input type="button" οnclick="setCookie()" value="设置cookie"/>
<input type="button" οnclick="delCookie()" value="删除cookie"/>
<input type="button" οnclick="showCookie()"value="显示cookie"/>
</body>
</html>
关于cookie的读写操作就介绍到这里了。欢迎交流~
摘自:http://hi.baidu.com/kuntakinte/item/08d2fb3297ba40c32e8ec219