利用js对COOKIE的增加、删除操作

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js对cookie操作</title>
<script language="javascript" src="include/cookie.js"></script>
</head>
<body>
<input name="keyid[]" type="checkbox" id="keyid11" onclick="changeCookie(this,&apos;11&apos;)" value="11" />
<input name="keyid[]" type="checkbox" id="keyid22" onclick="changeCookie(this,&apos;22&apos;)" value="22" />
<input name="keyid[]" type="checkbox" id="keyid33" onclick="changeCookie(this,&apos;33&apos;)" value="33" />
<input name="keyid[]" type="checkbox" id="keyid44" onclick="changeCookie(this,&apos;44&apos;)" value="44" />
<input name="keyid[]" type="checkbox" id="keyid55" onclick="changeCookie(this,&apos;55&apos;)" value="55" />
<label>
<input type="text" name="textfield" />
</label>
<input type="text" name="textfield2" />
<input type="text" name="textfield3" />
<script language="javascript">
allCookie();
</script>

</body>
</html>

//js

// JavaScript Document
//设定COOKIE,outTime=1为1天
function setCookie(cookieName,cookieValue,outTime)
{
 var str=cookieName+&apos;=&apos;+escape(cookieValue);//编码以适合任何浏览器
 if(outTime<0){
  var mm=outTime*3600*1000*24;
  var date =new Date();
  date.setTime(date.getTime()+mm);
  str+=&apos;;expires=&apos;+date.toGMTString();
 }
 document.cookie=str;
}
//删除COOIKIE
function delCookie(cookieName)
{
 var date=new Date();
 date.setTime(date.getTime()-10000);
 document.cookie=cookieName+&apos;=0;expires=&apos;+unescape(date.toGMTString());
}
//得到COOKIE的值
function getCookie(cookieName)
{
 var arrCookie=document.cookie.split(&apos;;&apos;);
 for(var i=0;i<arrCookie.length;i++){
  var arrName=arrCookie[i].split(&apos;=&apos;);
 
  if(arrName[0]==cookieName){alert(&apos;cookie名:&apos;+cookieName+&apos;数组cookie名:&apos;+arrName[0]);
   return unescape(arrName[1]);
  }else{
   alert(&apos;cookie名:&apos;+cookieName+&apos;数组cookie名:&apos;+arrName[0]+&apos;=&apos;+arrName[1]);
  }
 }
}
//===========以下是针对项目写的对COOKIE的操作======================
//按复选框时改变COOKIE的状态
function changeCookie(obj,cookieName)
{
 if(obj.checked==true){
  setCookie(cookieName,1);
 }else if(obj.checked==false){
  delCookie(cookieName);
 }
 alert(document.cookie);
}
//设置对应复选框的COOKIE的值,当cookieName为1时设为选中状态
function allCookie()
{alert(document.cookie);
 var checkboxList=document.getElementsByName("keyid[]");
 for(var i=0;i<checkboxList.length;i++){
  getCookie(checkboxList[i].value);
  if(getCookie(checkboxList[i].value)==1){
   checkboxList[i].checked=true;
  }
 }
}


此教程来源于97xxoo教程网(http://www.97xxoo.org/)查看完整的教程请点:http://www.97xxoo.org/article/1/2008/20081115351.shtml

posted on 2008-11-16 08:24  测试者家园  阅读(7005)  评论(0编辑  收藏  举报

导航