Html 在本地存储中设置变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16245536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setting a variable in local storage
提问by Lewis Waldron
Currently designing a game and the idea is that of a high score, so that when the current score is more than the local storage one it is replaced:
目前正在设计一款游戏,思路是高分,这样当当前的分数大于本地存储的时候就替换掉:
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
Thanks guys
谢谢你们
回答by Anthony Ledesma
This should point you in the correct direction.
这应该为您指明正确的方向。
// 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;
回答by Xotic750
Here is an example of what I think you are trying to achieve. Of course this is just an example and not the code written for you.
这是我认为您正在努力实现的一个示例。当然,这只是一个示例,而不是为您编写的代码。
<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);
On jsfiddle
Use the buttons to set the highscore, either 10 or 12. Refresh page, or hit run(only simulates a refresh). The user always scores 11 and it will alert either 11 or 12 depending on the saved highscore.
使用按钮设置高分,10 或 12。刷新页面,或点击运行(仅模拟刷新)。用户总是得分 11,它会根据保存的高分提醒 11 或 12。