<!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,'11')" value="11" />
<input name="keyid[]" type="checkbox" id="keyid22" onclick="changeCookie(this,'22')" value="22" />
<input name="keyid[]" type="checkbox" id="keyid33" onclick="changeCookie(this,'33')" value="33" />
<input name="keyid[]" type="checkbox" id="keyid44" onclick="changeCookie(this,'44')" value="44" />
<input name="keyid[]" type="checkbox" id="keyid55" onclick="changeCookie(this,'55')" 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+'='+escape(cookieValue);//编码以适合任何浏览器
if(outTime<0){
var mm=outTime*3600*1000*24;
var date =new Date();
date.setTime(date.getTime()+mm);
str+=';expires='+date.toGMTString();
}
document.cookie=str;
}
//删除COOIKIE
function delCookie(cookieName)
{
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=cookieName+'=0;expires='+unescape(date.toGMTString());
}
//得到COOKIE的值
function getCookie(cookieName)
{
var arrCookie=document.cookie.split(';');
for(var i=0;i<arrCookie.length;i++){
var arrName=arrCookie[i].split('=');
if(arrName[0]==cookieName){alert('cookie名:'+cookieName+'数组cookie名:'+arrName[0]);
return unescape(arrName[1]);
}else{
alert('cookie名:'+cookieName+'数组cookie名:'+arrName[0]+'='+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