2013-04-26 99 views
5

目前正在設計一個遊戲,這個想法是,一個高分的,所以,當目前的得分比本地存儲一個更多的則是替代:設置在本地存儲變量

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 

謝謝你們

+2

你的問題是什麼? – nullability 2013-04-26 21:32:21

+0

如何修復它,因爲它不工作? – 2013-04-26 21:41:44

+0

定義不起作用 – 2013-04-26 21:43:30

回答

10

這應該指向正確的方向。

// 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; 
1

這是我想你試圖實現的一個例子。當然這只是一個例子,而不是爲你寫的代碼。

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

jsfiddle

使用按鈕來設置高分,無論是10或12刷新頁面,或按運行(只模擬刷新)。用戶總是得分11,並且根據保存的高分將會提醒11或12。