HTML5/CSS3跨平台开发技术分享(三)

js操作cookie存取数据实例与分析(三)

上篇文章接着写,上次讲到存取数据,现在主要介绍删除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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值