简体   繁体   中英

HTML5 Local Storage, displaying saved date on refresh

I have currently been making a web app where users input score predictions for football games. I have managed to get the user to input scores, the score prediction appears on the screen and users can also delete the data if they want. However, on refreshing the page, the data is not there to be seen, and I want it to stay there.

Can anyone recommend how I could do this?

Thanks, here's my Javascript code.

    var timestamp=Date.now();


function doFirst(){
    var button = document.getElementById("button");
    button.addEventListener("click", saveStuff, false);
}



function saveStuff(){
    var one = document.getElementById("one").value;
    var two = document.getElementById("two").value;

    localStorage.setItem("one"+timestamp,one+","+two);          
    display();
    document.getElementById("one").value = "";
    document.getElementById("two").value = "";
}

function display(){
    var section2 = document.getElementById("sectiontwo");
    section2.innerHTML = document.getElementById("one").value+" - "+document.getElementById("two").value+"<br />";
}



function deleteKey(){
    document.getElementById("sectiontwo").innerHTML="";
    localStorage.removeItem(localStorage.key(localStorage.length-1));       


}


function clearAll(){
    localStorage.clear();
    document.getElementById("clear").style="visibility:hidden";
}

window.addEventListener("load", doFirst, false);

Here is my HTML code.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Premier League Site</title>
    <link rel="stylesheet" href="style.css"/>
    <script src="elliot.js"></script>
</head>
<body>
<script src="elliot.js"></script>
    <div id="wrapper">
    <header id="header">
    <h1>Premier League Site</h1>
    </header>

    <nav id ="Menu_Bar">
    <ul>
        <li>Home</li>
        <li>Teams</li>
        <li>Extras</li>
    </ul>

    </nav>

    <section id="sectionone">
    What is the score for Game one?
        <form>
            <p>(key) One: <input type="number" id="one"></p>
            <p>(value) Two <input type="number" id="two"></p>
            <p><input type="button" id="button" value="Save"></p>
            <p><input type="button" id="dbutton" value="Delete" onclick="deleteKey()"></p>
            <p><input type="button" id="clear" value="Clear All" onclick="clearAll();" ></p>
        </form>
    </section>
    <section id="sectiontwo">
        Stored Info should go here
    </section>  
    <footer id="footer">
        Elliot Harrison 2014
    </footer>
    </div>
</body>
</html>

I would suggest to store the data in an array / map object, and then de-serialize into json (string) data because local storage does allow to store only string data (use JSON.stringify() for that purpose).

For instance, you would need following objects in your json data: { createdTime, scoreResult, gameId as foreign key }.

Let say you enter "Game1" into the "key" text field, 1 for the first team and 2 for the second team, and then press "Save":

var arrResultList = JSON.parse(window.localstorage.getItem("FootballScoreData")); //global variable
if(typeof arrResultList === 'undefined' || arrResultList === null) {
    arrResultList = [];
}

function save() {
    var gameId = document.getElementById("gameId").value;
    var firstScore = document.getElementById("firstTeam").value;
    var secondScore = document.getElementById("secondTeam").value;

    arrResultList.push(new ScoreData(gameId, firstScore, secondScore));

    window.localstorage.setItem("FootballScoreData", JSON.stringify(arrResultList));
}

function ScoreData(gameId, firstScore, secondScore) {
    var _self = this;

    _self.createdTime = Date.now();
    _self.score = firstScore + '-' + secondScore;
    _self.gameId = gameId;
}

Your "display" function could be something like this:

function display() {
    var text = "";
    for (var i=0, length=arrResultList.length; i<length; i++) {
        text = text + arrResultList[i].score + "<br />";
    }
    section2.innerHTML = text;
}

And your deleteAll function:

function deleteAll() {
    arrResultList = [];
    window.localstorage.setItem("FootballScoreData", JSON.stringify(arrResultList));
}

If you want to delete certain item in the array, you can delete them by its time stamp for instance, but that should be easy I believe so :)

I post only the basic stuffs, but if you need more instruction / information, please email me.

You might also want to check Web SQL storage (instead of local storage) http://dev.w3.org/html5/webdatabase/ , if you want to develop the application further and need more complex structure.

Additionally, check out AngularJS or Knockout if you want to have two-way data binding support and other fancy stuffs.

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