H5之Web存储

2015-09-02  本文已影响163人  机器猫的百宝袋

客户端储存数据
1.两种方式:
a.localStorage - 没有时间限制的数据储存
b.sessionStorage - 针对一个session的数据存储 有时间限定,浏览器关闭

2.与cookie对比:
之前都是cookie存储,但cookie不适合大量数据的存储,因为他们由每个对服务器的请求来传递,这使得cookie速度很慢而且效率不高

localStorage

.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="localStorage.js"></script>
</head>
<body>
    <textarea style="width: 200px; height: 200px;" id="ta"></textarea>
    <button id="btn">save</button>
</body>
</html>

localStorage.js文件

var ta;
var btn;
window.onload = function(){
    ta = document.getElementById("ta");
    if(localStorage.text){
        ta.value = localStorage.text;
    }

    btn = document.getElementById("btn");
    btn.onclick = function(){
        //alert(ta.value);
        localStorage.text = ta.value;
    }

}

sessionStorage

.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="sessionStorage.js"></script>
</head>
<body>
    <span id="txt">0</span>
    <button id="addbtn">Add</button>
</body>
</html>

sessionStorage.js文件

var num = 0;
var txt;
var btn;
window.onload = function(){
    txt = document.getElementById("txt");
    btn = document.getElementById("addbtn");
    if(sessionStorage.num){
        num = sessionStorage.num;
    }else{
        num = 0;
    }

    btn.onclick = function(){
        num++;
        sessionStorage.num = num;
        showNum();
    }
}

function showNum(){
    txt.innerHTML = num;
}
上一篇下一篇

猜你喜欢

热点阅读