简体   繁体   中英

How to store Results using localStorage.setItem and to create a table with 'PlayerName' and 'TotalScore'

I'm currently learning Javascript & HTML and would like some advice.

I've created a very basic quiz using the following Javascript code and I'd like to store the PlayerName and TotalScore in a dynamic table which uses the localStorage functionality available, at the moment I'm simply storing the current PlayerName and TotalScore using the Document.write function in my HTML page, any thoughts, Can anyone help ?

I thought about creating an array called ListOfNames but unsure how to continually add to it the next time the browser opens without declaring the variable as just [ ] again ?

var getUsername = false;
var playerName = "string";

playerName = prompt("Please state your player name");
while( getUsername == false)    {
         if (confirm("Are you happy with " + playerName + " ?\n Press OK to proceed 
                                                    OR Cancel to change player name")) {
                                    getUsername = true;
                                     }
        else {
                playerName = prompt("Please provide a valid player name");
                                    }
                                };

alert("  Welcome to my Quiz \n\nPlease answer the following questions as 
accurately as possible \n\nI will then give you a totalscore at the end");

var totalScore = 0;

var question1 = prompt("              Question 1.\n\nWhich country is José 
Mourino from?");
            if (question1 == "Portugal" || question1 =="portugal") {
                totalScore++;
              };
            alert("You Scored " +totalScore + " out of a possible 1");
            alert("Well done");


var listOfPlayers = [];
listOfPlayers.push(playerName);
localStorage.listOfPlayers = listOfPlayers;
console.log(listOfPlayers);

My HTML is currently set like this which correctly populates the CURRENT playerName and score, I would like to store the ONGOING results and consistently grow the table among friends etc ::

  <table class="table">
   <thead>
     <tr>
       <th>Player Name</th>
       <th>Score</th>
     </tr>
   </thead>
   <tbody>
      <tr class="success">
        <td><script> document.write(playerName)</script></td>
        <td><script> document.write(totalScore)</script></td>
     </tr>
     <tr class="success">
       <td>Liam</td>
       <td>11</td>
       </tr>

You should not use document.write() as this is an ancient way to include content into a document and leads to JavaScript having to be written in the correct sequence (as you've found out) and can lead to overwriting of the document if you aren't careful.

Instead, you can have the skeleton of a table hard-coded in your page (as you have done), but use the API for a table element to dynamically add rows, cells and cell content to it as needed.

Here's an example:

 // Place the following code in a <script> element that comes // just before the closing body tag (</body>) // Get references to the table and the button. var btnAdd = document.getElementById("btnAddRow"); var tbl = document.getElementById("tblOutput"); // Set up a click event handling function for the button btnAdd.addEventListener("click", function(){ // Set up array for new data. The data can come from anywhere. // Here, I'm just hard coding it. var data = ["Scott", "999", "42"]; // Create a new row on the table var row = tbl.insertRow(); // Loop through the array to insert the data into the cells of the new row // and to store the data in localStorage data.forEach(function(value, index){ // Insert a cell in the row at correct index var newCell = row.insertCell(index); // Place content from the array in the cell - this can be any data from anywhere newCell.textContent = value; }); // Append the array to previously stored data localStorage.setItem("playerData", localStorage.getItem("playerData") + data.join(",")); }); 
 /* Just some styling for the table */ table, td, th { border:1px solid black; } td { padding: 3px; } tr:nth-child(even){ background-color:rgba(255, 255, 0, .3); } 
 <table id="tblOutput"> <thead> <th>Name</th> <th>ID</th> <th>Level</th> </thead> </table> <button id="btnAddRow">Add New Row</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM