How to use local storage in JavaScript and output the stored elements in a table?

后端 未结 1 968
一个人的身影
一个人的身影 2021-01-15 02:42

I created a "mini-game". It is simply a reaction tester. All you do is try to click on the squares and circles as fast as you can.

What I want to do now is

相关标签:
1条回答
  • 2021-01-15 03:05

    Here's a quick live demo of how you can use HTML local storage to save a list of high scores, then retrieve it and put the data into a table structure. The demonstration script takes a list of high scores, stores it to local storage, retrieves it from local storage, then displays it in a table.

    Since localStorage isn't supported by Stack Snippet, here is a JSFiddle that demonstrates the code: https://jsfiddle.net/fsze55x7/1/

    HTML:

    <table id="highscores">
        <tr><td>Name</td><td>Score</td></tr>
    </table>
    

    JS:

    var hst = document.getElementById("highscores");
    
    var highScores = [
        {name: "Maximillian", score: 1000},
        {name: "The second guy", score: 700},
        {name: "The newbie", score: 50},
    ];
    
    localStorage.setItem("highscores", JSON.stringify(highScores));
    
    var retrievedScores = JSON.parse(localStorage.getItem("highscores"));
    
    for (var i = 0; i < retrievedScores.length; i++) {
        hst.innerHTML += "<tr><td>" + retrievedScores[i].name + "</td><td>" + retrievedScores[i].score + "</td></tr>";
    }
    
    0 讨论(0)
提交回复
热议问题