2015-10-05 108 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