2015-10-05 105 views
-2

我正在使用javascript和html制作游戏。我想创建一个高分功能。 x是您当前得分的名称。在下面的代码中,header表示“高分”,但在完成游戏后应该说出一个数字。Javascript Highscore Not Working

<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 ; 
} 
} 

注意:下面的代码表示[对象HTMLHeadingElement]而不是“高分”

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 ; 

可有人请告诉我我哪里错了

+4

凡'x'意味着神奇来自:

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 ; 

所以它不使用HTML元素,以便定义highscore之外的功能? –

+0

*“x是您当前得分的名称。”*,请告诉我们您是如何获得该价值的。确保它是你的想法,而不是HTML元素。 –

回答

0

如果x只是一个数字保证您在函数highscorefunction之外定义了highscore,那么您的浏览器正在将全局变量highscore解释为对该HTML元素的引用,因为它的ID

var highscore = localStorage.getItem("highscore"); 
function highscorefunction() { 
    ... 
} 
document.getElementById("highscore").textContent = highscore ; 
+0

我会做那条线而不是localStorage.setItem(“highscore”,x); }或其下面 – 987654321

+0

@ 987654321你会沿着'localStorage.setItem(“highscore”,x.innerHTML)''的方向行事。 –

+0

x是一个javascript变量,而不是来自HTML – 987654321