標籤:
早期的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講解