我试图通过使用localStorage在Snake游戏中设置高分,但是我无法使其正常工作。我可以得到一些建议吗?
这是使用Javascript的Cloud9。
<div id = "highscore">High Score: 0</div>
var highscore = 0;
var localStorage = localStorage;
localStorage.setItem("highscore", highscore);
var storage = localStorage.getItem("highscore");
highscore.innerHTML = storage;
if (score > highscore) {
highscore = score;
}
我希望高分能够保留在localStorage中,但是由于某些原因却没有。
答案 0 :(得分:1)
如果得分大于高分,则将得分设置为本地存储
if (score > highscore) {
highscore = score;
localStorage.setItem("highscore", highscore);
}
答案 1 :(得分:0)
您可以使用Cookie来存储高分
即
var highscore = parseInt(getCookie("high_score"));
if (score > highscore) {
document.cookie = "high_score="+ score + ";";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
答案 2 :(得分:0)
我是这样解决的: 您的最高分会保存到 localstorege 中,并且会在游戏结束后始终更新并从 localstorege 加载到您的 HTML 代码中。
var highscore = localStorage.getItem("highscore");
document.getElementById('highscore').innerHTML = localStorage.getItem("highscore");
if (highscore < score) {
highscore = score
localStorage.setItem("highscore", highscore);
}