2013-04-26 96 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。