JavaScript 使用cookie做为计数器
html文件:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How many times have you been here before?</title>
<script type="text/javascript" src="script04.js"></script>
</head>
<body bgcolor="#FFFFFF">
<h2 id="pageHits"> </h2>
</body>
</html>
javascript文件:
window.onload = initPage;
function initPage() {
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);
var hitCt = parseInt(cookieVal("pageHit"));
hitCt++;
document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
document.getElementById("pageHits").innerHTML = "You have visited this page " + hitCt + " times.";
}
function cookieVal(cookieName) {
var thisCookie = document.cookie.split("; ");
//这里为什么会得到pageHit=24 我没有设置过pageHit的值。
for (var i=0; i<thisCookie.length; i++) {
if (cookieName == thisCookie[i].split("=")[0]) {
return thisCookie[i].split("=")[1];
}
}
return 0;
}