6

目前设计一个游戏,想法是高分,所以当当前分数超过本地存储时,它被替换:

localStorage.setItem('highScore', highScore);
var HighScore = localStorage.getItem('highScore');
if (HighScore == null || HighScore == "null") {
  HighScore = 0;
}

if (user.points > HighScore) {
  highScore = parseInt(HighScore);
}
return highScore 

多谢你们

4

2 回答 2

14

这应该为您指明正确的方向。

// Get Item from LocalStorage or highScore === 0
var highScore = localStorage.getItem('highScore') || 0;

// If the user has more points than the currently stored high score then
if (user.points > highScore) {
  // Set the high score to the users' current points
  highScore = parseInt(user.points);
  // Store the high score
  localStorage.setItem('highScore', highScore);
}

// Return the high score
return highScore;
于 2013-04-26T21:46:34.940 回答
3

这是我认为您正在努力实现的目标的示例。当然,这只是一个示例,并不是为您编写的代码。

<button id="save10">Save 10</button>
<button id="save12">Save 12</button>

var highscore = 11,
    button10 = document.getElementById("save10"),
    button12 = document.getElementById("save12"),
    savedHighscore;

function saveData(x) {
    localStorage.setItem('highscore', x);
}

button10.addEventListener("click", function () {
    saveData(10);
}, false);

button12.addEventListener("click", function () {
    saveData(12);
}, false);

savedHighscore = parseInt(localStorage.getItem('highscore'), 10);
if (typeof savedHighscore === "number" && highscore <  savedHighscore) {
    highscore = savedHighscore;
}

alert("Highscore: " + highscore);

jsfiddle 上

使用按钮设置高分,10 或 12。刷新页面,或点击运行(仅模拟刷新)。用户总是得分 11,它会根据保存的高分提醒 11 或 12。

于 2013-04-26T22:01:20.057 回答