问题
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
回答1:
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;
回答2:
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.
来源:https://stackoverflow.com/questions/16245536/setting-a-variable-in-local-storage