HTML本地存储

时间:2013-12-15 20:18:53

标签: javascript html5 local-storage

我正在尝试将信息存储在本地存储中 在使用数据填充表单后,我想将表单及其内容保存在本地存储中,但由于某种原因,一旦我提交信息并刷新页面信息未保存,它就无法工作 任何建议

<!--local Storage-->
<!DOCTYPE html>
<html>
<head>
<script>
function info()
{
    if(typeof(Storage)!=="undefined"){
        var fn = document.getElementById("FirstName").value;
        var ln = document.getElementById("LastName").value;
        var zc = document.getElementById("zipcode").value;

        localStorage.FastName = fn;
        localStorage.FirstName = ln;
        localStorage.Zipcode = zc;

        document.getElementById("result").innerHTML=localStorage.FastName+" "+" "+localStorage.FirstName+" "+localStorage.Zipcode;
    }else{
        document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
    }

}
</script>
</head>
<body>
<p>fill in your information:</p>
First name: <input type="text" id="FirstName" value=""><br>
Last name: <input type="text" id="LastName" value=""><br>
Zip Code: <input type="text" id="zipcode" value="" >
<p><button onclick="info();" type="button">Submit</button></p>
<div id="result"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可能希望使用localStorage.setItem("FirstName", fn);将值写入localStorage。

如果要在重新加载时在输入字段中返回值,则需要在应用程序启动时通过读取localStorage中的值(通过getItem)填充输入字段。

e.g。追加到最后

<script>
document.getElementById("FirstName").value = localStorage.getItem("FirstName");
...
</script>