我正在使用javascript和html制作游戏。我想设置一个高分功能。 x
是您当前得分的名称。在下面的代码中,header
表示“高分”,但在我玩完游戏后应该说一个数字。
<h2 id="highscore">Highscore</h2>
function highscorefunction() {
var highscore = localStorage.getItem("highscore");
if(highscore !== null){
if (x > highscore) {
localStorage.setItem("highscore", x );
document.getElementById("highscore").textContent = highscore ;
}
}else{
localStorage.setItem("highscore", x );
document.getElementById("highscore").textContent = highscore ;
}
}
注意:下面的代码表示[object HTMLHeadingElement]而不是“highscore”
function highscorefunction() {
var highscore = localStorage.getItem("highscore");
if(highscore !== null){
if (x > highscore) {
localStorage.setItem("highscore", x );
}
}else{
localStorage.setItem("highscore", x );
}
}
document.getElementById("highscore").textContent = highscore ;
有人可以告诉我出错的地方
答案 0 :(得分:0)
如果x
只是一个数字,请确保在函数highscore
之外定义highscorefunction
,您的浏览器会将全局变量highscore
解释为对该HTML元素的引用通过 id 。
function highscorefunction() {
// Local variable "highscore"
var highscore = localStorage.getItem("highscore");
...
}
// global variable "highscore", referring the HTML with the id of "highscore"
document.getElementById("highscore").textContent = highscore ;
因此,在函数外部定义highscore
,以便它不使用HTML元素:
var highscore = localStorage.getItem("highscore");
function highscorefunction() {
...
}
document.getElementById("highscore").textContent = highscore ;