通过Javascript将Cookie值增加1 [英] Incrementing Cookie Value by 1 via Javascript

查看:39
本文介绍了通过Javascript将Cookie值增加1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,它们来自 w3schhols.com 中的 Reading Setting Cookie .我在增加Cookie的值时遇到问题

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

但不是将值从 1 递增到 2 .它实际上是在将价值放在旁边:- 11 -> 111 -> 1111 ,依此类推.

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.

我该如何增加cookie值.

How could i increment cookie value.

谢谢

推荐答案

它是一个字符串,您需要先将其强制转换:

Its a string, you need to cast it first:

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

这篇关于通过Javascript将Cookie值增加1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆