JQuery IndexedDB是一個方便的工具,它可以幫助你在瀏覽器中存儲和檢索數據,并且還可以幫助你管理IndexedDB的對象倉庫。
//打開IndexedDB數據庫 var request = window.indexedDB.open("myDatabase", 1); request.onerror = function(event) { console.log("打開Database失敗"); }; request.onsuccess = function(event) { var db = event.target.result; console.log("打開Database成功"); }; //創建一個對象倉庫 request.onupgradeneeded = function(event) { var db = event.target.result; var objectStore = db.createObjectStore("customers", { keyPath: "id" }); // 創建索引 objectStore.createIndex("name", "name", { unique: false }); objectStore.createIndex("email", "email", { unique: true }); console.log("對象倉庫創建成功"); };
使用JQuery IndexedDB可以實現以下操作:
1. 添加一個對象到對象倉庫
//指定對象倉庫和對象 var request = db.transaction(["customers"], "readwrite") .objectStore("customers") .add({ id: 12345, name: "張三", email: "zhangsan@gmail.com" }); request.onsuccess = function(event) { console.log("添加成功"); }; request.onerror = function(event) { console.log("添加失敗"); }
2. 更新一個對象
//指定對象倉庫和對象 var request = db.transaction(["customers"], "readwrite") .objectStore("customers") .put({ id: 12345, name: "李四", email: "lisi@gmail.com" }); request.onsuccess = function(event) { console.log("更新成功"); }; request.onerror = function(event) { console.log("更新失敗"); }
3. 刪除一個對象
//指定對象倉庫和對象id var request = db.transaction(["customers"], "readwrite") .objectStore("customers") .delete(12345); request.onsuccess = function(event) { console.log("刪除成功"); }; request.onerror = function(event) { console.log("刪除失敗"); }
4. 通過索引查詢對象
//指定對象倉庫和索引名稱 var objectStore = db.transaction("customers").objectStore("customers"); var index = objectStore.index("name"); //查詢名稱為張三的對象 index.get("張三").onsuccess = function(event) { console.log(event.target.result); };
需要注意的是,JQuery IndexedDB并沒有包含所有IndexedDB的功能,因此在使用過程中需要注意兼容性和功能的支持情況。
上一篇篩選樣式css