JavaScript Cookie我获得了NaN属性

时间:2014-03-14 21:05:03

标签: javascript cookies

我试图在document.cookie中的javascript中保存一个数字。 但是当我试图获得一个带有数字的cookie时,我试图显示它时总是得到NaN

var playerCoffeeCount = 0;
function setCookie(c_name, value, exdays) { //Setting a cookie (just a shortcut for making cookies)
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) { //Getting a cookie (another shortcut)
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function saveGame(){
    setCookie("playerCoffeeCookie", playerCoffeeCount, 999);
}
function loadGame(){
    playerCoffeeCount = getCookie("playerCoffeeCookie");
}
function displayCookie(){
    document.getElementById("coffeecount").innerHTML= "Coffee: " + Math.floor(playerCoffeeCount);
}

JavaScript中的这个cookie系统保存了值,但它显示为NaN ...请帮助:(

1 个答案:

答案 0 :(得分:0)

试试这个,运作良好。

 function createCookie(name,days,value) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) { //cookie reader function
        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) { //cookie eraser function
        createCookie(name,"",-1);
    }

    createCookie("test", 1, 1);
    var mycookie= readCookie("test");
    mycookie = parseFloat(mycookie);
    console.log(mycookie);

console log