html5 localStorage講解

來源:互聯網
上載者:User

標籤:

早期的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 + ‘\n發表時間:‘+(new Date()).toDateString() +‘\n‘;            }else{                localStorage.storage = content.value + ‘\n發表時間:‘+(new Date()).toDateString() +‘\n‘;            }            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 =‘沒有內容!‘        }    }}

 

html5 localStorage講解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.