Jam*_*een 16 javascript cookies
我想在每次引用页面时递增cookie值,即使页面是从缓存加载的.实现这一目标的"最佳"或最简洁的方法是什么?
nic*_*ckf 30
从http://www.quirksmode.org/js/cookies.html#script窃取
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toUTCString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Run Code Online (Sandbox Code Playgroud)
使用它:
var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);
Run Code Online (Sandbox Code Playgroud)
正如评论中所指出的,你应该转换为int,因为cookie被存储并作为字符串返回.使用foo++或++foo将为您实际投射,但更准确地知道您正在使用的内容更安全:
var x = "5"; // x = "5" (string)
x += 1; // x = "51" (string!)
x += 5; // x = "515" (string!)
++x; // x = 516 (number)
Run Code Online (Sandbox Code Playgroud)
我见过的大多数旧的cookie处理函数都使用简单的字符串操作来存储检索值,比如这个例子,你可以使用其他库,比如cookie-js,一个小的(<100行)实用程序来访问cookie.
我个人在我的项目中使用jQuery,并且我使用jQuery Cookie插件,它使用起来非常简单:
var cookieName = "increment";
if ($.cookie(cookieName) == null){
$.cookie(cookieName, 1, { expires: 10 });
}else{
var newValue = Number($.cookie(cookieName)) + 1;
$.cookie(cookieName, newValue, { expires: 10 });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16625 次 |
| 最近记录: |