我有以下用于读取
和设置Cookie
的代码,取自w3schhols.com
。我在增加 Cookie 的值时遇到问题
function isNumber (o) {
return ! isNaN (o-0) && o !== null && o.replace(/^\s\s*/, '') !== "" && o !== false;
}
function setCookie(c_name,value,exdays)
{
var date=new Date();
date.setTime( date.getTime() + (exdays*24*60*60*1000) );
expires='; expires=' + date.toGMTString();
document.cookie=c_name + "=" + value + expires + '; path=/';
}
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
我正在使用以下函数来递增:-
function addToCart() {
var totalcart = getCookie("totalcart");
if (totalcart != null && totalcart != "" && isNumber(totalcart)) {
totalcart += 1;
setCookie('totalcart',totalcart, 2);
jQuery('#totalcart').text(totalcart);
} else {
setCookie('totalcart', 1 , 2);
jQuery('#totalcart').text('1');
}
}
但不是将值从 1
增加到 2
。它实际上是把值(value)放在一边:-
11
-> 111
-> 1111
等等。
如何增加 cookie 值。
谢谢
最佳答案
它是一个字符串,你需要先转换它:
var totalcart = parseInt(getCookie("totalcart"));
关于javascript - 通过 Javascript 将 Cookie 值加 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163044/