以前我们在本地存储数据都是用document.cookie来存储的,但是由于其的存储大小只有4k左右,解析也很复杂,给开发带来了诸多的不便.不过现在html5出了web的存储,弥补了cookie的不足,而且开放起来也是相当的方便
web存储分两类
sessionstorage
容量大小约为5m左右,该方式的生命周期为关闭浏览器窗口为止
localstorage
容量大小约为20m左右, 存储的数据不会随着用户浏览时会话过期而过期,但会应用户的请求而删除。浏览器也因为存储空间的限制或安全原因删除它们.而且类型存储的数据可以同一个浏览器的多个窗口共享
注意点:只能存储字符串,如果是json对象的话,可以将对象json.stringify() 编码后存储
方法详解:
setitem(key, value) 设置存储内容
getitem(key) 读取存储内容
removeitem(key) 删除键值为key的存储内容
clear() 清空所有存储内容
下面我们就给个给大家看一下他的写法:
//更新
    function update() {
        window.sessionstorage.setitem(key, value);
    }    //获取
    function get() {
        window.sessionstorage.getitem(key);
    }    //删除
    function remove() {
        window.sessionstorage.removeitem(key);
    }    //清空所有数据
    function clear() {
        window.sessionstorage.clear();
    }
查看效果的话,我们以谷歌浏览器为例子:
以前的老版本的话,是没有application的,老版本的为resource
存储完数据后的
下面我就给大家展示记录用户名和密码的经典例子
当记住密码的复选框勾上的时候,下次打开的时候,用户名和密码就不需要在重新输入了
 html部分:
<label for="">
        用户名: <input type="text" class="username"/>
    </label>
    <br/><br/>
    <label for="">
        密 码: <input type="password" class="pwd"/>
    </label>
    <br/><br/>
    <label for="">
        <input type="checkbox" class="ckb"/>
        记住密码
    </label>
    <br/><br/>
    <button>登录</button>
js部分
var username=document.queryselector('.username');    var pwd=document.queryselector('.pwd');    var sub=document.queryselector('button');    var ckb=document.queryselector('.ckb');
    sub.onclick=function(){//        如果记住密码 被选中存储,用户信息
        if(ckb.checked){
            window.localstorage.setitem('username',username.value);
            window.localstorage.setitem('pwd',pwd.value);
        }else{
            window.localstorage.removeitem('username');
            window.localstorage.removeitem('pwd');
        }//        否则清除用户信息    }
    window.onload=function(){//        当页面加载完成后,获取用户名,密码,填充表单
        username.value=window.localstorage.getitem('username');
        pwd.value=window.localstorage.getitem('pwd');
    }
以上就是html5的web存储的详细内容。
   
 
   