Cookie返回undefined

时间:2015-12-10 20:09:50

标签: javascript cookies

我正在构建一个使用cookies / localStorage来保存和加载用户数据的小型HTML游戏。我声明了一个对象,它保存了所有数据,然后由保存/加载函数和游戏计算引用:

var iAttack, iDefence, iGold;
// nothing to do with Apple lol...

var data = {
    pStats: {
        attack: iAttack,
        defence: iDefence
    },
    pInventory: {
        gold: iGold
    }
}

这些显然会返回undefined,但这是在插入cookie值之前。 因此,继续讨论应该发生的事情:

当窗口加载时,if语句经过检查cookies / localStorage以及浏览器中是否有任何先前的存储数据。这些布尔值已分配到cookiesstorageLocalpreviousData。这是它的代码:

var previousData = false;
var cookies = false;
var storageLocal = false;

//activated on window.load
function loadData(){



//check for previous data
    if (document.cookie != "") {
        previousData = true;
        console.log("Previous data? " + previousData)
    } else if (localStorage.getItem("gold") !== null) {
        previousData = true;
        console.log("Previous data? " + previousData)
    } else {
        console.log("Previous data? " + previousData)
    }


    // check if cookies/localStorage
    document.cookie = "foo=bar";
    if(document.cookie){
        cookies = true;
        console.log("Cookies will be used")
    } else if (typeof(localStorage) != undefined){
        storageLocal = true;
        console.log("localStorage will be used")
    }

    // loadData() continued...

如果previousData = false则将默认值分配给对象变量,例如iDefence = 5,这样可以正常工作。

让我们假设previousDatacookiestrue:然后函数继续将cookie中的数据插入到对象变量中,如下所示:

if (previousData) {    
        if (cookies){
            data.pStats.attack = parseInt( readCookie("attack") );
            data.pStats.defence = parseInt( readCookie("defence") );
            // note that i've used iAttack instead of data.pStats.attack but doesn't work

在控制台中,如果我输入iAttackdata.pStats.attack,则会返回undefined。这是让我在昨晚试图解决问题的问题。任何帮助都会非常感激。

这是onclick触发的saveData函数。它将对象值输入到cookie中:

function saveData(){
    if(cookies){
        createCookie("attack", iAttack, 7);
        createCookie("defence", iDefence, 7);
        //if its the first time saving then the default values of iAttack/def will be used

如果您对createCookie()readCookie()感到好奇,可以使用以下功能:

function createCookie(name,value,days) {
    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) {
    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) {
    createCookie(name,"",-1);
}

0 个答案:

没有答案