当前位置: 代码迷 >> HTML/CSS >> html5当地存储 localStorage
  详细解决方案

html5当地存储 localStorage

热度:399   发布时间:2013-02-24 17:58:56.0
html5本地存储 localStorage
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312">
        <title>HTML5每日一练之JS API-本地存储LocalStorage | 前端开发网(W3Cfuns.com)!</title>
        <script type="text/javascript">
                window.onload = function()
                {
                        alert("当你关闭此页面或者关闭浏览器的时候,localStorage中保存的数据才会消失,也就是说重新打开此页面的时候,点击获取数据,可以取到数据。")
                       
                        //首先获得body中的3个input元素
                        var msg = document.getElementById("msg");
                        var getData = document.getElementById("getData");
                        var setData = document.getElementById("setData");
                       
                        setData.onclick = function()//存入数据
                        {
                                if(msg.value)
                                {
                                        localStorage.setItem("data", msg.value);
                                        alert("信息已保存到data字段中");
                                }
                                else
                                {
                                        alert("信息不能为空");
                                }
                        }
                       
                        getData.onclick = function()//获取数据
                        {
                                var msg = localStorage.getItem("data");
                                if(msg)
                                {
                                        alert("data字段中的值为:" + msg);
                                }
                                else
                                {
                                        alert("data字段无值!");
                                }
                        }
                }
        </script>
    </head>
   
    <body>
            <input id="msg" type="text"/>
        <input id="setData" type="button" value="保存数据"/>
        <input id="getData" type="button" value="获取数据"/>
    </body>
</html>