方法屬性 |
描述 |
setItem(key,value) |
該方法接收一個鍵名和值作為參數,將會把鍵值對添加到存儲中,如果鍵名存在,則更新其對應的值 |
getItem(key) |
該方法接收一個鍵名作為參數,返回鍵名對應的值 |
romoveItem(key) |
該方法接收一個鍵名作為參數,并把該鍵名從存儲中刪除 |
length |
類似數組的length屬性,用于訪問Storage對象中item的數量 |
key(n) |
用于訪問第n個key的名稱 |
clear() |
清除當前域下的所有localSotrage內容 |
代碼示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>localStorage</title> </head> <body> <input type="text" id="username" > <input type="button" value="localStorage 設置數據 " id="localStorageId"> <input type="button" value="localStorage 獲取數據 " id="getlocalStorageId"> <input type="button" value="localStorage 刪除數據 " id="removesessionStorageId"> <script> document.getElementById("localStorageId").onclick=function(){ // 把用戶在 input 里面數據的數據保存到 localStorage var username=document.getElementById("username").value; window.localStorage.setItem("username",username); }; document.getElementById("getlocalStorageId").onclick=function(){ // 獲取數據,從 localStorage var username=window.localStorage.getItem("username"); alert(username); }; document.getElementById("removesessionStorageId").onclick=function(){ // 刪除 localStorage 中的數據 var username=document.getElementById("username").value; window.localStorage.removeItem("username"); }; </script> </body> </html>
sessionStorage 主要用于區域存儲,區域存儲是指數據只在單個頁面的會話期內有效。由于 sessionStroage 也是 Storage 的實例, sessionStroage 與 localStorage 中的方法基本一致,唯一區別就是存儲數據的生命周期不同, locaStorage 是永久性存儲,而 sessionStorage 的生命周期與會話保持一致,會話結束時數據消失。
2.3sessionStorage實現區域存儲
從硬件方面理解, localStorage 的數據是存儲子在硬盤中的,關閉瀏覽器時數據仍然在硬盤上,再次打開瀏覽器仍然可以獲取,而 sessionStorage 的數據保存在瀏覽器的內存中,當瀏覽器關閉后,內存將被自動清除,需要注意的是, sessionStorage 中存儲的數據只在當前瀏覽器窗口有效。
代碼示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>sessionStorage</title> </head> <body> 姓名: <input type="text" id="username"> 年齡: <input type="text" id="age"> <input type="button" value="sessionStorage 設置數據 " 11 id="sessionStorageId"> <input type="button" value="sessionStorage 獲取數據 " id="getsessionStorageId"> <input type="button" value="sessionStorage 清除所有數據 " id="clearsessionStorageId"> <script> // 增加數據 document.getElementById("sessionStorageId").onclick = function() { // 獲取姓名和年齡輸入框的值 var username = document.getElementById("username").value; var age = document.getElementById("age").value; // 定義一個 user 對象用來保存獲取的信息 var user = { username: username, age: age } // 使用 stringify() 將 JSON 對象序列號并存入到 sessionStorage window.sessionStorage.setItem("user",JSON.stringify(user)); }; //sessionStorage 里面存儲數據,如果關閉了瀏覽器,數據就會消失 .. // 單個瀏覽器窗口頁面有效 document.getElementById("getsessionStorageId").onclick = function() { var valu = window.sessionStorage.getItem("user"); alert(valu); }; // 清除所有的數據 document.getElementById("clearsessionStorageId").onclick = function() { window.sessionStorage.clear(); }; </script> </body> </html>
3 總結
HTML5中的兩種存儲方式都比較實用,我們在設計前端頁面時,可以根據相應的用戶訪問情況預測來增添相應的js,既增加了用戶瀏覽的體驗,又能實現存儲管理的高效性,合理的利用存儲空間。
到此這篇關于HTML5中的網絡存儲的文章就介紹到這了,更多相關html5 網絡存儲內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章,希望大家以后多多支持腳本之家!