HTML5存储

<input type="text" placeholder="请输入姓名" id="name">
    <input type="phone" placeholder="请输入电话" id="phone">
    <button onclick="storage()">点击</button>
    <p id="result"></p>
    <p id="times"></p>
    <p id="sname"></p>
    <script>
        //存储
        var re=document.getElementById('result');
        var times=document.getElementById('times');
        if(typeof(Storage)!="undifine"){
            localStorage.setItem('lastName','Gates');
            //alert(localStorage.getItem('lastName'));
            re.innerHTML=localStorage.getItem('lastName');
        }else{
            re.innerHTML="抱歉!您的浏览器不支持Web Storage";
        }
        //查看访问次数,存储,关闭浏览器,再打开浏览器还在
        if(localStorage.pagecount){
            localStorage.pagecount=Number(localStorage.pagecount)+1;
        }else{
            localStorage.pagecount=1;
        }
        //sessionStorage访问次数,关闭浏览器,本地存储也会消失
        if(sessionStorage.pagecount){
            sessionStorage.pagecount=Number(sessionStorage.pagecount)+1;
        }else{
            sessionStorage.pagecount=1;
        }
        times.innerHTML="您访问的次数是localStorage:"+localStorage.pagecount+"您访问的次数是sessionStorage:"+sessionStorage.pagecount;
        //存储表单内容
        function storage(){
            var name=document.getElementById('name').value;
            var phone=document.getElementById('phone').value;
            var user={name:name,phone:phone};//JSON形式
            //alert(user.name);
            localStorage.setItem("user",JSON.stringify(user));//存储时将JSON形式转化成字符串形式
            var sname=JSON.parse(localStorage.getItem('user')).name;
            //getItem获取了字符串,JSON.parse将字符串形式转化成JSON形式,之后取JSON数据里面的name值,即存储的name值
            //alert(sname);
            document.getElementById('sname').innerHTML=sname;
            
            
        }
        //清除存储的内容
        localStorage.setItem('name','zz');
        alert(localStorage.getItem('name'));
        localStorage.removeItem('name');
        alert(localStorage.getItem('name'));
    

 

posted @ 2017-05-19 17:19  freeah  阅读(174)  评论(0编辑  收藏  举报