用cookie实现叶卡的记忆功能

之前在写叶卡切换的时候总需要把js代码写到html标签里面。

后来接触了闭包后知到一点点怎么通过闭包实现该功能。

之后又想通过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=utf-8" />
<title>test</title>
<style type="text/css">
.cl{
clear:both;
}
#menu{
width:600px;
height:30px;
}
#menu div{
display:inline;
float:left;
border:1px solid #
000;
margin
-left:4px;
width:80px;
height:30px;
line
-height:30px;
padding:6px;

}
#menu .menu_on{
background:#FFC;
margin
-bottom:-1px;
height:31px;
}

#content{
border:1px solid #
000;
width:600px;
margin
-left:4px;
}
.c_off{
display:none;
}
</style>
</head>

<body>
<div id="menu">
<div class="menu_off">浙江</div>
<div class="menu_off">沪鲁</div>
<div class="menu_off">中西部</div>
<div class="menu_off">其他</div>
</div>
<div id="content" class="cl">
<div class="c_off">浙江</div>
<div class="c_off">沪鲁</div>
<div class="c_off">中西部</div>
<div class="c_off">其他</div>
</div>
<script type="text/javascript">
myMenu
=document.getElementById("menu");
menuDiv
=myMenu.getElementsByTagName("div");
myContent
=document.getElementById("content");
contentDiv
=myContent.getElementsByTagName("div");
window.onload
=function(){
cookieId
=1;
cookieId
=getCookie('menuId');
menuDiv[cookieId].className
="menu_on";
contentDiv[cookieId].className
="c_on";
for(var i=0;i<menuDiv.length;i++)
{
menuDiv[i].index
=i;
(function(myid)
{

menuDiv[i].onclick
=function()
{
for(var i=0;i<menuDiv.length;i++)
{
menuDiv[i].className
="menu_off";
contentDiv[i].className
="c_off";
}
this.className="menu_on";
contentDiv[myid].className
="c_on";
cookieId
=this.index;
setCookie(
'menuId',cookieId,365);
}
})(i);
}
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start
=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start
=c_start + c_name.length+1
c_end
=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}

function setCookie(c_name,value,expiredays)//名称,值,过期时间
{
var exdate
=new Date()
exdate.setDate(exdate.getDate()
+expiredays)//setDate() 方法用于设置一个月的某一天。调整过的日期的毫秒表示。getDate月份中的某一天,使用本地时间。返回值是 1 ~ 31 之间的一个整数。
document.cookie
=c_name+ "=" +escape(value)+//escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。可以使用 unescape() 对 escape() 编码的字符串进行解码。
((expiredays
==null) ? "" : "; expires="+exdate.toGMTString())//expires为过期时间。toGMTString() 方法可根据格林威治时间 (GMT) 把 Date 对象转换为字符串,并返回结果。不赞成使用此方法。请使用 toUTCString() 取而代之!
}
</script>
</body>
</html>
posted @ 2011-09-06 23:13  穹天  阅读(160)  评论(0编辑  收藏  举报