Posted on 2012-04-15 16:37
zljpp 閱讀(247)
評(píng)論(0) 編輯 收藏
一、 DEMO HTML代碼
上一次介紹了HTML5 Web Storage存儲(chǔ)機(jī)制,原來必須保存在服務(wù)端數(shù)據(jù)庫中的內(nèi)容現(xiàn)在可以直接保存在客戶端本地了,這不僅可以減輕了服務(wù)器數(shù)據(jù)訪問的負(fù)擔(dān),同時(shí)也提高了數(shù)據(jù)的訪問速度。請(qǐng)將下面的代碼復(fù)制到html文件中,我們通過示例來了解Web Storage。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>HTML5 Web Storage示例</title> <script type="text/javascript" src="JS/webstoragescript.js"> </script> </head> <body> <div> <h2>sessionStorage示例</h2> <p id="sessionMsg"></p> <input type="text" id="sessionInput"> <input type="button" value="保存數(shù)據(jù)" onClick="savesessionStorage('sessionInput');"> <input type="button" value="讀取數(shù)據(jù)" onClick="loadsessionStorage('sessionMsg');"> <br /> <h2>localStorage示例</h2> <p id="localMsg"></p> <input type="text" id="localInput"> <input type="button" value="保存數(shù)據(jù)" onClick="savelocalStorage('localInput');"> <input type="button" value="讀取數(shù)據(jù)" onClick="loadlocalStorage('localMsg');"> </div> </body> </html> |
上為DEMO HTML代碼
當(dāng)我們點(diǎn)擊保存數(shù)據(jù)時(shí),分別調(diào)用webstoragescript.js(代碼在文章后面)中的savesessionStorage和savelocalStorage方法,點(diǎn)擊讀取數(shù)據(jù)時(shí)分別調(diào)用loadsessionStorage和loadlocalStorage方法。
讓我們打開JS腳本文件來看下,該腳本分別使用了sessionStorage和localStorage兩種方法。這兩種方法的HTML代碼只有p id和input id不同 ,都是當(dāng)用戶在input文本輸入內(nèi)容并點(diǎn)擊保存數(shù)據(jù)按鈕時(shí)保存數(shù)據(jù),點(diǎn)擊讀取數(shù)據(jù)時(shí)讀取保存的數(shù)據(jù)。
但是他們對(duì)數(shù)據(jù)的處理方式都不一樣,sessionStorage方法如果關(guān)閉了瀏覽器,這個(gè)保存的數(shù)據(jù)就丟失,在一次打開瀏覽器瀏覽這個(gè)頁面的時(shí)候,點(diǎn)擊讀取數(shù)據(jù)將讀取不到任何數(shù)據(jù)。
而localStorage則是瀏覽器被關(guān)閉,下次在打開瀏覽器瀏覽這個(gè)頁面點(diǎn)擊讀取數(shù)據(jù)時(shí)任然能讀取到保存的數(shù)據(jù)。當(dāng)然,這個(gè)數(shù)據(jù)是區(qū)分瀏覽器的,在別的瀏覽器中是讀取不到這個(gè)瀏覽器保存的數(shù)據(jù)的。
二、兩種對(duì)象使用方法
1.sessionStorage
保存數(shù)據(jù):sessionStorage.setItem(key,value);
讀取數(shù)據(jù):sessionStorage.getItem(key);
2.localStorage
保存數(shù)據(jù):localStorage.setItem(key,value);
讀取數(shù)據(jù):localStorage.getItem(key);
看上面的說明相信大家都能很快明白兩種對(duì)象的使用方法。但是,不管是使用哪個(gè)對(duì)象,都是用setItem(鍵名,鍵值)的方法來保存數(shù)據(jù),保存后不允許修改鍵名,但是可以修改鍵值也就是說只新建鍵名,再保存鍵值。使用getItem方法讀取數(shù)據(jù)時(shí),將參數(shù)指定為鍵名,返回鍵值。
// sessionStorage示例JS function savesessionStorage(id){ var target= document.getElementById(id); var str=target.value; sessionStorage.setItem("message",str); }
function loadsessionStorage(id){ var target=document.getElementById(id); var msg=sessionStorage.getItem("message"); target.innerHTML=msg; }
// localStorage示例JS function savelocalStorage(id){ var target= document.getElementById(id); var str=target.value; localStorage.setItem("message",str); }
function loadlocalStorage(id){ var target=document.getElementById(id); var msg=localStorage.getItem("message"); target.innerHTML=msg; } |
webstoragescript.js代碼

火狐瀏覽器中的HTML5 Web Storage示例