当前位置: 首页 > 工具软件 > web3.storage > 使用案例 >

HTML5 Web Storage用法

华凯捷
2023-12-01
<!DOCTYPE html >
    <head>
            <title>演示HTML5 Web Storage的用法</title>
  </head>
<body>
        <div id="storageDiv">
                <form id="storageForm">
                        <article>
                            <section>
                                    <span>姓名:</span>
                                    <input type="text" name="name" id="name">
                            </section>
                            <section>
                                    <span>年龄:</span>
                                    <input type="text" name="age" id="age">
                            </section>
                            <section>
                                    <span>生日:</span>
                                    <input type="text" name="birthday" id="birthday">
                            </section>
                        </article>
                        <section>
                                <input type="button" οnclick="save2Storage();" value="本地存储">
                                <input type="button" οnclick="loadFromStorage();" value="从本地存储加载">
                                <input type="button" οnclick="javascript:localStorage.removeItem('pageCount');" value="从本地存储中删除pagecount">
                                <input type="button" οnclick="javascript:localStorage.clear();" value="从本地存储中删除">
                        </section>
                </form>
        </div>
        <div id="footer"></div>
<script>
    // localStorage:本地存储,永久保存。
    // 统计页面访问人数
    var pageCount = localStorage.getItem("pageCount");
     
    if (pageCount != null && pageCount != undefined) {
        localStorage.setItem("pageCount",parseInt(pageCount) + 1); 
    }
    else {
            localStorage.setItem("pageCount",1);
    }
     
    document.getElementById("footer").innerHTML="This page has been visited " + localStorage.getItem("pageCount") + " times";  
     
    // sessionStorage:一个会话周期内有效,关闭浏览器窗口后失效。
  // 用法同localStorage
     
    function save2Storage() {
        var frm = document.getElementById('storageForm');
         
        var formData = {
            'name':frm.name.value,
            'age':frm.age.value,
            'birthday':frm.birthday.value  
        }; 
 
        localStorage.setItem('formData',JSON.stringify(formData));
        alert("数据保存成功!");
    }
     
    function loadFromStorage() {
        var formData = localStorage.getItem('formData');
         
        if (formData!=null) {
            formData = JSON.parse(formData);
            var frm = document.getElementById('storageForm');
            frm.name.value = formData.name;
            frm.age.value = formData.age;  
            frm.birthday.value = formData.birthday;
            alert("数据加载完毕!");
        }  
    }
</script>
</body>
</html>
HTML5 Web Storage介绍及用法请参考:http://www.cnblogs.com/amtf/archive/2012/02/19/2355693.html
 类似资料: