2013-04-26 21 views
5

attualmente progettando un gioco e l'idea è quella di un punteggio alto, in modo che quando il punteggio attuale è più che memoria locale lo si è sostituito:impostare una variabile nella memoria locale

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 

Grazie ragazzi

+2

Qual è la tua domanda? – nullability

+0

Come posso risolvere il problema perché non funziona? –

+0

define not working –

risposta

10

Questo dovrebbe indicare la direzione corretta.

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

Ecco un esempio di ciò che penso si stia tentando di raggiungere. Ovviamente questo è solo un esempio e non il codice scritto per te.

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

Su jsfiddle

utilizzare i pulsanti per impostare il punteggio, o 10 o 12. Aggiorna pagina, o correre colpire (simula solo un aggiornamento). L'utente segna sempre 11 e avviserà 11 o 12 a seconda del punteggio salvato.