JavaScript 使用cookie做为计数器

baixueaiaide2008 2014-09-09 08:18:20
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;
}
...全文
173 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
KK3K2005 2014-09-10
  • 打赏
  • 举报
回复
document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString(); 你这里不是一直在设置
2.wa 2014-09-10
  • 打赏
  • 举报
回复
我这测试没有问题 推荐使用 cooks.js 方便多了 http://blog.csdn.net/xiaohulunb/article/details/28303327

87,984

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧