<script language="JavaScript" type="text/JavaScript">
<!--
function addcookie(name,value,expireHours){
var cookieString=name+"="+escape(value);
//判断是否设置过期时间
if(expireHours>0){
var date=new Date();
date.setTime(date.getTime+expireHours*3600*1000);
cookieString=cookieString+"; expire="+date.toGMTString();
}
document.cookie=cookieString;
}
//-->
</script>
2.获取指定名称的cookie值:getcookie(name)
该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下:
复制代码 代码如下:
<script language="JavaScript" type="text/JavaScript">
<!--
function getcookie(name){
var strcookie=document.cookie;
var arrcookie=strcookie.split("; ");
for(var i=0;i<arrcookie.length;i++){
var arr=arrcookie[i].split("=");
if(arr[0]==name)return arr[1];
}
return "";
}
//-->
</script>
3.删除指定名称的cookie:deletecookie(name)
该函数可以删除指定名称的cookie,其实现如下:
复制代码 代码如下:
<script language="JavaScript" type="text/JavaScript">
<!--
function getcookie(name){
var strcookie=document.cookie;
var arrcookie=strcookie.split("; ");
for(var i=0;i<arrcookie.length;i++){
var arr=arrcookie[i].split("=");
if(arr[0]==name)return arr[1];
}
return "";
}
//-->
</script>
也可以用另一种网上流传的:
复制代码 代码如下:
<script language="JavaScript" type="text/JavaScript">
function SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值
{
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name)//删除cookie
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
SetCookie ("xiaoqi", "3")
alert(getCookie('xiaoqi'));
</script>
您可能感兴趣的文章: