早期的web中使用cookies在客戶端保存諸如用戶名等簡單的信息,可是,在使用cookies存儲永久數據存在如下問題。javascript
1.cookies的大小限制在4kB,不適合大量的數據存儲。css
2.瀏覽器還限制站點能夠在用戶計算機上存儲的cookies的數量。html
3 cookies是隨HTTP事務一塊兒被髮送的,所以會浪費一部分帶寬。java
HTML5很好的提供了本地存儲的功能,以鍵值對存儲的解決方案,支持容量至少爲4M,HTML5的web提供了兩種客戶端存儲方式。web
1.localStorage:是一種沒有時間限制的數據存儲方式,能夠將數據永久保存在客戶端。瀏覽器
sessionStorage:指的是針對一個session的數據存儲,即將數據保存在session對象中,當關閉瀏覽器後,這些數據就被刪除。cookie
在使用web存儲以前,應該先檢查一下瀏覽器是否支持localStorage和sessionStorage(I7如下不支持)session
判斷方法spa
if(typeof(localStorage !=='undefined'){localstorage
};
或者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 ='沒有內容!' } } }