html5 localStorage讲解

早期的web中使用cookies在客户端保存诸如用户名等简单的信息,但是,在使用cookies存储永久数据存在以下问题。

1.cookies的大小限制在4kB,不适合大量的数据存储。

2.浏览器还限制站点可以在用户计算机上存储的cookies的数量。

3 cookies是随HTTP事务一起被发送的,因此会浪费一部分带宽。

HTML5很好的提供了本地存储的功能,以键值对存储的解决方案,支持容量至少为4M,HTML5的web提供了两种客户端存储方式。

1.localStorage:是一种没有时间限制的数据存储方式,可以将数据永久保存在客户端。

sessionStorage:指的是针对一个session的数据存储,即将数据保存在session对象中,当关闭浏览器后,这些数据就被删除。

在使用web存储之前,应该先检查一下浏览器是否支持localStorage和sessionStorage(I7以下不支持)

判断方法

if(typeof(localStorage !=='undefined'){

};

或者if(window.localStorage){

}

web Storage支持的属性与方法

getItem(key):获取指定key所存储的value值

key(index)方法:返回列表中对应索引的key值

length属性:返回key/value队列的长度

removeItem(key)方法:从Storage中删除一个对应的键值对。

setItem(key,value)方法:将value存储到key指定的字段。

clear()方法:移除所有的内容

注意:设置,获取key/value的方法除了使用setItem()和getItem()方法以外,还分别提供了一个简单的方法:设置方法:sessionStorage.someKey = 'someValue'

获取方法:alert(sessionStorage.someKey);

下面一个例子来说明一下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link href="localstorage.css" type="text/css" rel="stylesheet"/>
    <script src="Storage.js" type="text/javascript"></script>

</head>
<body>
<input id="t1" type="text" />
<button id ="add"  >添加</button>
<button id ='remove'>删除</button><br/>
<textarea id="t2" readonly="readonly"></textarea>
</body>
</html>

css

#t2{
    width:500px;
    height:400px;
    margin-top:10px;
}

js

window.onload = function(){
    var content = document.getElementById('t1');
    var btn1 = document.getElementById('add');
    var btn2 =document.getElementById('remove');
    btn1.addEventListener('click',SaveInfo);
    btn2.addEventListener('click',clearInfo);
    function SaveInfo(){
        if(typeof localStorage !=='undefined'){
            if(localStorage.storage){
                localStorage.storage += content.value + '
发表时间:'+(new Date()).toDateString() +'
';
            }else{
                localStorage.storage = content.value + '
发表时间:'+(new Date()).toDateString() +'
';
            }
            ShowInfo()
        }else {
            alert('无法存储!')
        }
    }

    function clearInfo(){
        localStorage.removeItem('storage');
        ShowInfo()
    }

    function ShowInfo(){
        var txt = document.getElementById('t2');
        if(localStorage.storage){
            txt.value =localStorage.getItem('storage');
        }else{
            txt.value ='没有内容!'
        }
    }
}
原文地址:https://www.cnblogs.com/yuaima/p/5906153.html