简体   繁体   English

HTML5本地存储,刷新时显示保存的日期

[英]HTML5 Local Storage, displaying saved date on refresh

I have currently been making a web app where users input score predictions for football games. 我目前正在制作一个Web应用程序,用户可以在其中输入足球比赛的得分预测。 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. 谢谢,这是我的Javascript代码。

    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. 这是我的HTML代码。

<!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). 我建议将数据存储在数组/映射对象中,然后反序列化为json(字符串)数据,因为本地存储确实只允许存储字符串数据(为此目的使用JSON.stringify())。

For instance, you would need following objects in your json data: { createdTime, scoreResult, gameId as foreign key }. 例如,您将需要在json数据中包含以下对象:{createdTime,scoreResult,gameId作为外键}。

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": 假设您在“键”文本字段中输入“ Game1”,第一个团队输入1,第二个团队输入2,然后按“保存”:

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: 和您的deleteAll函数:

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. 如果您想进一步开发应用程序并需要更复杂的结构,则可能还需要检查Web SQL存储(而不是本地存储) http://dev.w3.org/html5/webdatabase/

Additionally, check out AngularJS or Knockout if you want to have two-way data binding support and other fancy stuffs. 另外,如果您想获得双向数据绑定支持和其他花哨的东西,请查看AngularJS或Knockout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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