IDBTransaction: objectStore() 方法
注意:此功能在 Web Workers 中可用。
IDBTransaction 介面的 objectStore() 方法會返回一個已經新增到此事務範圍內的物件儲存空間。
在同一事務物件上,使用相同的名稱呼叫此方法,每次都會返回同一個 IDBObjectStore 例項。如果此方法在不同的事務物件上呼叫,則會返回一個不同的 IDBObjectStore 例項。
語法
js
objectStore(name)
引數
name-
所請求物件儲存的名稱。
返回值
一個用於訪問物件儲存的 IDBObjectStore 物件。
異常
NotFoundErrorDOMException-
如果所請求的物件儲存不在此事務的範圍內,則會丟擲此異常。
InvalidStateErrorDOMException-
如果在已刪除或移除的源物件上發出請求,或者事務已完成,則會丟擲此異常。
示例
在以下程式碼片段中,我們打開了一個數據庫的讀/寫事務,並向一個物件儲存中添加了一些資料。同時,還注意到了附加到事務事件處理程式上的函式,用於在成功或失敗時報告事務開啟的結果。完整的可執行示例,請參閱我們的 待辦事項通知 應用(線上檢視示例)。
js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
}
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-objectstore① |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。