2013-04-26 16 views
5

Obecnie projektując grę i chodzi o to, że od wysoki wynik, tak, że kiedy obecny wynik jest więcej niż lokalne przechowywanie jednej to otrzymuje:ustawienie zmiennej w pamięci lokalnej

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 

Dzięki chłopaki

+2

Jakie jest twoje pytanie? – nullability

+0

Jak to naprawić, ponieważ nie działa? –

+0

Zdefiniuj niedziałający –

Odpowiedz

10

Powinno to wskazywać właściwy kierunek.

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

Oto przykład tego, co myślę, że próbujesz osiągnąć. Oczywiście jest to tylko przykład, a nie kod napisany dla ciebie.

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

Na jsfiddle

pomocą przycisków, aby ustawić wysoki wynik, 10 lub 12. Odśwież stronę, lub uderzyć bieg (tylko symuluje odświeżenia). Użytkownik zawsze otrzymuje 11 punktów, a alarmuje 11 lub 12 w zależności od zapisanego rekordu.

Powiązane problemy