Javascript / HTML5 - 在本地存储中存储和显示分数

时间:2017-06-04 15:58:27

标签: javascript html5

我用分数创建了一个游戏。每次发生碰撞时,它会广告10分,当用户进行16次碰撞时,游戏结束,分数会存储在本地存储中,因此可以在记分板上显示。

  //everytime there's a collision, contador++
  // when contador reaches 16, there's a pop up and the score is saved in local storage.

  if (contador == 16)  {

  localStorage.setItem("pontosSalvos", pontos);

  var pop = document.getElementById ( "alerta_ajuda");
  pop.style.display = 'inline';
  contador = 0;

          }

然后,记分板的页面包含以下代码:

    //the score gets displayed on a span called mensagem

    function mostraPontos() {
    var pontos = localStorage.getItem ("pontosSalvos");
    var span = document.getElementById ("mensagem_pontos");

    span.innerHTML = pontos; 
}

我想知道的是: 使用这样的代码,只要有新分数,它就会替换记分板中的先前分数,并且只显示新分数。 有没有办法存储/显示多个分数而不替换旧分数? 谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将分数推送到数组并将其字符串化版本保存到localStorage,而不是存储单个值。

要在HTML中显示它们,您应该解析从localStorage返回的字符串值以再次获取数组,并将其值映射到您选择的HTML元素。

这样的事情:



const board = document.getElementById('board');

// Load saved scores:

const fakeLocalStorage = {};

let scores = [];

try {
  scores = JSON.parse(fakeLocalStorage.scores);
} catch(err) {}

// Add new scores and save them:

document.getElementById('push').onclick = function() {  
  scores.push(Math.floor(Math.random() * 17));
  
  fakeLocalStorage.scores = JSON.stringify(scores);
  
  board.innerHTML = scores.map(score => `<li>${ score }</li>`).join('');
};

// Clear all scores and delete them from localStorage:

document.getElementById('clear').onclick = function() {
  scores = [];
  
  delete fakeLocalStorage.scores;
  
  board.innerHTML = '';
};
&#13;
<button id="push">ADD SCORE</button>
<button id="clear">CLEAR SCORES</button>

<ul id="board"></ul>
&#13;
&#13;
&#13;

注意:StackOverflow片段中不允许localStorage,所以我在这个例子中只使用普通对象fakeLocalStorage。您可以在代码中将其替换为localStorage,它仍应按预期工作。

答案 1 :(得分:0)

localStorage只能存储字符串。您可以使用多种格式在其中存储数组。我建议JSON这样做。有一些带有分数的数组,当从localStorage读取时,JSON.parse它,以及写入时,JSON.stringify。您可能希望将范围更改为有序列表。

if (contador == 16)  {
    var pontosArr = JSON.parse(localStorage.pontosSalvos || '[]');
    pontosArr.push(+pontos);
    // Sorts highest to lowest
    pontosArr.sort(function(a, b) { return b - a; });
    localStorage.pontosSalvos = JSON.stringify(pontosArr);

    var pop = document.getElementById ( "alerta_ajuda");
    pop.style.display = 'inline';
    contador = 0;

}
function mostraPontos() {
    // pontos is an empty array if nothing has been stored yet.
    var pontos = JSON.parse(localStorage.pontosSalvos || '[]');
    var ol = document.getElementById("mensagem_pontos");
    ol.innerHTML = '';
    // Appends all the scores as list elements
    for (var i = 0; i < pontos.length; i++) {
        var li = document.createElement('li');
        li.textContent = pontos[i];
        ol.appendChild(li);
    }
}