Incrementing Cookie Value by 1 via Javascript

被刻印的时光 ゝ 提交于 2021-02-05 11:41:17

问题


I have below code for Reading and Setting Cookie taken from w3schhols.com. I have problem while incrementing the value of 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;
}

And I am using below function to increment :-

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');
}
}

But instead of Incrementing Value from 1 to 2. It is actually putting value beside it :- 11 -> 111 -> 1111 and so on and so forth.

How could i increment cookie value.

Thanks


回答1:


Its a string, you need to cast it first:

var totalcart = parseInt(getCookie("totalcart"));



回答2:


Because when you retrieve the value from the cookie it is a string, this means when you add the 1 to the end it acts as a string. You need to use parseInt function to convert your string to an int, so you can run your equation.

function addToCart() {
var totalcart = parseInt(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');
}
} 


来源:https://stackoverflow.com/questions/19163044/incrementing-cookie-value-by-1-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!