cookie.js
/**
days:有效日期
*/
function writeCookie(name,value,days){
var expires = "";
if(days){
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie += name + "=" + value + expires + "; path=/";
alert( document.cookie);
}
function readCookie(name){
var searchName = name + "=";
//alert(document.cookie);
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++){
var c = cookies[i];
while(c.charAt(0) == ' '){
c = c.substring(1,c.length);
}
if(c.indexOf(searchName) == 0){
return c.substring(searchName.length,c.length);
}
}
return null;
}
function eraseCookie(name){
writeCookie(name,"",-1);
}
html
<!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>求和</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="cookies.js"></script>
<script type="text/javascript">
function alrt(){alert(document.body.clientHeight +" " + document.body.clientWidth);}
var index = 1;
function testCookie(){
//document.body.onresize = alrt;
var name = readCookie("name");
if(!name){
document.getElementById("name").innerHTML = "名字为空";
writeCookie("name","duoduo",5);
}else{
document.getElementById("name").innerHTML = name;
writeCookie("name"+index,"duoduo"+ ++index,5);
}
}
$(function(){
//$("#button").click();
alert(navigator.cookieEnabled);
testCookie();
document.getElementById("button").onclick = testCookie;
});
</script>
</head>
<body>
<div id="name"></div>
<button id="button">点击</button>
</body>
</html>