这个本地存储代码有什么问题吗?

时间:2015-09-17 21:14:53

标签: javascript debugging local-storage

我是初学者,我只是编写有趣的代码并制作一些简单的项目。这个月我正在努力制作赛马“游戏”。这个游戏是第一个使用本地存储的项目,所以我对如何编码它并不熟悉。由于w3学校和MDN,我对它有了基本的了解,但仍然有很多错误。最让我烦恼的是名字改变功能。在我的代码中,您可以单击一个按钮,然后提示将要求您为该匹配一个新名称。然后,屏幕显示它,并将值保存到变量和本地存储。但是,当我重新加载页面时,名称不会更改,并且屏幕仍显示默认名称。有什么方法可以解决这个问题吗?

var horse = {
    energy: false,
    name: false,
    speed: false,
    money: false,
    busy: false,
    hayBale: false,
};

//these are my LS checks and loads...
if(localStorage.getItem("energy") === false) {
    localStorage.setItem("energy", 100);
}
if(localStorage.getItem("name") === false) {
    localStorage.setItem("name", "Give your horse a name!");
}
if(localStorage.getItem("speed") === false) {
    localStorage.setItem("speed", 0);
}
if(localStorage.getItem("busy") === false) {
    localStorage.setItem("busy", 0);
}
if(localStorage.getItem("hayBale") === false) {
    localStorage.setItem("hayBale", 0);
}
if(localStorage.getItem("money") === false) {
    localStorage.setItem("money", 0);
}
horse.name = localStorage.getItem("name");
horse.speed = parseFloat(localStorage.getItem("speed"), 10);
horse.busy = parseInt(localStorage.getItem("busy"), 10);
horse.hayBale = parseInt(localStorage.getItem("hayBale"), 10);
horse.money = parseInt(localStorage.getItem("money"), 10);
horse.energy = parseInt(localStorage.getItem("energy"), 10);

//and this is my name changing function.
$("#horseName").click(function() {
    var newName = prompt("What do you want to rename your horse to? (the name is changable at any time)");
    if(newName !== "" && newName !== false) {
        alert("Success! Your horse is now named '" + newName + "'!");
        document.getElementById("horseName").innerHTML = newName;
        horse.name = newName;
        localStorage.setItem("name", newName);
    } else {
        alert("You didn't enter a name!");
    }
});

2 个答案:

答案 0 :(得分:1)

初始检查值是否已存在是错误的,因此每次刷新时都会再次设置默认值。

当项目不存在时,

Storage.getItem()会返回null,因此请检查false <而不是null(这是要存储的有效值)。 / p>

if(localStorage.getItem("name") === null) { // check for null instead of false
    localStorage.setItem("name", "Give your horse a name!");
}

不要忘记为其他默认设置执行此操作。

答案 1 :(得分:0)

if(localStorage.getItem("energy") === false) {
    localStorage.setItem("energy", 100);
}

这里的目的是检查一个值是否已经存在于localstorage中,如果没有,则使用默认值对其进行初始化。如果没有指定值,你希望localStorage.getItem()函数返回false,这就是你的错误。

该功能很可能会返回null,因此您需要检查localStorage.getItem("key")是否返回null,而不是false

我还建议检查'undefined'值。请参阅此问题的答案:How can I check if a localstorage variable is null or undefined?

相关问题