从LocalStorage初始化变量

时间:2013-12-27 19:51:10

标签: javascript html5

我正在创建一个游戏,你点击一个马铃薯,然后你可以买土豆来购买增强剂(如cookieclicker)。我正在使用localStorage.setItem()和localStorage.getItem()来保存玩家拥有的土豆数量,这段代码运行正常:

var potatoes = 0;

function addPotato(amount)
{
    potatoes += amount;
    localStorage.setItem('potatoes', potatoes);

    if ( localStorage.getItem('potatoes') ) {
        document.getElementById("potatoes").innerHTML = "<b>Potatoes: </b>" + localStorage.getItem('potatoes'); 
    }
}

但我的问题是我重新加载页面后不会停留(因为var potatoes设置为0)。 我试过把它改成

var potatoes = 0;

if ( localStorage.getItem('potatoes') ) {
    potatoes = localStorage.getItem('potatoes'); 
}

但是由于一些奇怪的原因使得马铃薯的数量被附加到段落而不是覆盖它,所以如果我点击马铃薯5次而不是说5它说11111.是的,我知道玩家可以改变在当地可变,但这并不重要。

2 个答案:

答案 0 :(得分:3)

当您从localStorage获取该项时,它是一个字符串 - 对该值执行parseInt以将其转换回整数:

potatoes = parseInt(localStorage.getItem('potatoes'), 10);

答案 1 :(得分:2)

localStorage将所有内容存储为字符串。 ParseInt it