本地存儲localStorage設置存儲內容setItem(key,value) localStorage.setItem('leo','23'); 更新存儲內容對象[key]=value對象.key=value localStorage.leo = 25; localStorage['leo'] ...
本地存儲localStorage
設置存儲內容setItem(key,value)
localStorage.setItem('leo','23');
更新存儲內容
對象[key]=value
對象.key=value
localStorage.leo = 25;
localStorage['leo'] = 24;
獲取存儲內容getItem(key)
console.log(localStorage.getItem('leo'))
刪除存儲內容removeItem(key)
localStorage.removeItem('leo');
清空存儲內容clear()
localStorage.clear();
獲取存儲內容長度
console.log(localStorage.length);
sessionStorage
sessionStorage.a = 10;
console.log(sessionStorage);
localStorage與sessionStorage的區別
localStorage:
存儲會持久化
容量2-5MB
sessionStorage:
在網頁會話結束後失效
容量不一,部分瀏覽器不設限
Storage使用註意:
1、存儲容量超出限制,需要使用try catch捕獲異常
2、存儲類型限制:只能是字元串
3、sessionStorage失效機制:
刷新頁面不能使sessionStorage失效
相同URL不同標簽頁不能共用sessionStorage
滑鼠點擊掉血游戲案例:
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{margin: 0;padding: 0;list-style: none;} body{position: relative;height: 100%;} html{height: 100%;} .guai{position: absolute;left: 50%;top: 50%;margin: -75px 0 0 -100px;} .line{width: 400px;height: 20px;border:4px solid black;position: absolute;left: 50%;top: 20px;margin: 0 0 0 -204px;} .xie{width: 400px;height: 100%;background: red;transition: .3s;} </style> </head> <body> <div class='line'> <div class='xie'></div> </div> <img src="1.jpeg" class='guai'> <script type="text/javascript"> var num = 0,timer = null,max = 400, xieNode = document.querySelector('.xie'); if(localStorage.x){ max = localStorage.x; xieNode.style.width = max + 'px'; }; onclick = function(){ var r = Math.random() * 5 + 5; max -= r; localStorage.setItem('x',max); console.log(localStorage) xieNode.style.width = max + 'px'; clearInterval(timer); timer = setInterval(function(){ num++; if(num == 10){ clearInterval(timer); num = 0; document.body.style.left = 0; document.body.style.top = 0; return; }; document.body.style.left = Math.random() * -20 + 10 + 'px'; document.body.style.top = Math.random() * -20 + 10 + 'px'; },30) } </script> </body> </html>
一個帶過期機制的localStorage
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> 儲存數據: <input type="" name="" id='need'> 儲存數據的時間: <input type="" name="" id='timer'> <button id='btn'>保存</button> 數據展示: <span id='span'>暫無數據</span> <script type="text/javascript"> var nowTime = new Date().getMinutes(); if(nowTime >= localStorage.timer){ localStorage.clear(); } else{ if(localStorage.leo){ span.innerHTML = localStorage.leo; } } btn.onclick = function(){ localStorage.setItem('leo',need.value); localStorage.setItem('timer',new Date().getMinutes() + Number(timer.value)); span.innerHTML = localStorage.leo; }; </script> </body> </html>
HTML5 - 資料庫:indexedDB
創建資料庫indexedDB.open('隨便起個名字',版本號)
如果有這個數據就打開,沒有就創建
版本號只能往上走,不可以降
var request = indexedDB.open('testDBLeo',6);
onsuccess 資料庫創建或打開成功
onerror 打開失敗 (版本號不能降低)
onupgradeneeded 版本升級時觸發的函數
// 資料庫創建成功 request.onsuccess = function(){ console.log('創建資料庫成功'); }; // 資料庫創建失敗 request.onerror = function(){ console.log('資料庫讀取失敗'); }; // 資料庫版本升級 request.onupgradeneeded = function(){ console.log('版本號升級了') };
createObjectStore 創建一個表
自動遞增的 - createObjectStore 表裡面遞增
{autoIncrement: true}
{keyPath:數據中的欄位}
request.onupgradeneeded = function(){ var db = request.result; // 一個ObjectStore相當於一張表 // 指定表的主鍵自增 db.createObjectStore('test3',{autoIncrement: true}); };
設置主鍵為id
db.createObjectStore('test3',{keyPath: 'id'}
unique true 唯一性 如果有多個同樣的的情況下 就不寫入了
store.createIndex('test3','name',{unique:true});
transaction使用事務獲取表
readwrite 讀寫模式
readonly 只能讀不能寫
var transaction = db.transaction('test3','readwrite'); var store = transaction.objectStore('test3');
操作數據表
add 添加數據,添加 readonly 是報錯的
get 裡面放入key值就可以的
getAll 可以獲取所有的表中的數據 result 是以數組的形式表現
put 繼續添加數據
delete 刪除某一條數據 參數就是key值
clear 刪除所有的數據
onsuccess 如果指令成功了執行的回調函數
result 可以看到相關的數據
var json = [{ "id":200, "name":"Modoy", "age":"15" },{ "id":201, "name":"Busy", "age":"21" },{ "id":202, "name":"Blue", "age":"23" }] // add 添加數據 store.add(json); // 讀取數據store.get()參數是主鍵的值 var requestNode = store.get(1); //獲取成功後的操作 requestNode.onsuccess = function(){ console.log(requestNode.result); for(var i=0;i<3;i++){ console.log('名字叫'+requestNode.result[i].name); console.log('年齡今年已經'+requestNode.result[i].age+'歲了'); } };
更新指定主鍵的數據
store.put({ "id":203, "name":"Sky", "age":"29" });
獲取所有數據
var requestNode = store.getAll();
刪除指定id的數據
store.delete(201);
游標,此處表示主鍵<=202
var requestNode = store.openCursor(IDBKeyRange.upperBound(202)); requestNode.onsuccess = function(){ //獲取游標所取得的值 var cursor = requestNode.result; if(cursor){ console.log(cursor.value); cursor.continue(); }; };
索引 唯一性
store.createIndex(表名稱,數據key值,{unique:true}); ---------- var index = store.index(表的名稱)get(key值的名稱).onsuccess = function(){ e.target.result 找到的數據的內容 }
游標指定範圍:
IDBKeyRange.only//參數一是範圍
upperBound // 小於等於之前的 true 不包含自己的 false 包含自己的
lowerBound // 大於等於之前的 true 不包含自己的 false 包含自己的
bound 參數1 大於等於的 參數2 小於等於的 如果有參數 3 和 4 就是true 和 false
true 不包含自己的 false 包含自己的
參數3 對應著參數1 參數4 對應著參數2
設置游標的direction:
next 順序查詢
nextunique 順序唯一查詢
prev 逆序查詢
prevunique 逆序唯一查詢
var requestNode = store.openCursor(IDBKeyRange.bound(200,202),'prev');
索引和游標結合
//指定數據表 var index = store.index('test3'); //游標指定範圍 var requestNode = index.openCursor(IDBKeyRange.upperBound(31)); requestNode.onsuccess = function(){ var cursor = requestNode.result; if(cursor){ //如果查詢的數據name為Leo if(cursor.value.name == 'Leo'){ // 更新數據 cursor.update({ "id":209, "name":"Leoooo", "age":31 }); } console.log(cursor.value); cursor.continue(); } };
IndexedDB與Web Storage比較:
優點:IndexedDB存儲類型豐富
條件搜索強大
存儲容量更大
可以在Worker中使用
缺點:相容性問題