我正在尝试使用 jQuery Cookie 插件创建和存储 cookie。我想让cookie只是一个普通的计数器。我需要它是一个 cookie,因为我想在页面刷新时保持计数器继续运行。当某些条件成立时,我希望将 1 添加到 cookie 值中。看起来很简单,但我在使用该插件时遇到了麻烦。
我创建了这样的cookie:
$(document).ready(function(){
$.cookie("cookieValue", "0", { expires: 7 , path: '/' });
});
我想要实现的目标的一个小例子:
if (/*some condition*/) {
cokieValue++;
}
当条件为真时,这不起作用,cookie值保持为0。我也尝试过:
$(document).ready(function(){
$.cookie("cookieValue", "0", { expires: 7 , path: '/' });
var cookieValue = parseInt($.cookie("cookieValue"));
if (/*some condition*/) {
cookieValue++;
}
});
这也不起作用 - cookieValue 仍为 0。关于如何实现此目的有什么建议吗?
最佳答案
在将其更新为零之前,您需要检查它是否存在。
if( $.cookie('cookieValue') === null ) {
$.cookie( 'cookieValue', '0', { expires: 7, path: '/' } );
}
更新后需要保存该值。
$.cookie("cookieValue", cookieValue, { expires: 7 , path: '/' })
所以最终的代码看起来像这样
$(function(){ //shortcut for document.ready
var cookieVal = $.cookie("cookieValue"); //grab the cookie
if( cookieVal === null ) { //see if it is null
$.cookie( 'cookieValue', '0', { expires: 7, path: '/' } ); //set default value
cookieVal = 0; //set the value to zero
}
var cookieValue = parseInt(cookieVal,10); //convert it to number
if (/*some condition*/) {
cookieValue++; //increment the value
$.cookie("cookieValue", cookieValue, { expires: 7 , path: '/' }); //save new value
}
});
关于javascript - 使用cookie作为计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781864/