IDBObjectStore: clear() 方法
注意:此功能在 Web Workers 中可用。
IDBObjectStore 介面的 clear() 方法會建立一個 IDBRequest 物件並立即返回它,然後在一個單獨的執行緒中清除此物件儲存。此方法用於刪除物件儲存中的所有當前資料。
清除物件儲存包括從物件儲存中刪除所有記錄,以及刪除所有引用該物件儲存的索引中的記錄。要僅刪除儲存中的部分記錄,請使用 IDBObjectStore.delete 方法,並傳入一個鍵或 IDBKeyRange。
語法
js
clear()
引數
無。
返回值
一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。
如果操作成功,請求的 result 屬性的值將為 undefined。
異常
InvalidStateErrorDOMException-
如果物件儲存已被刪除,則丟擲此異常。
ReadOnlyErrorDOMException-
如果此操作關聯的事務處於只讀 模式,則丟擲此異常。
TransactionInactiveErrorDOMException-
如果此
IDBObjectStore的事務不活躍,則會丟擲此異常。
示例
在以下程式碼片段中,我們打開了資料庫的讀/寫事務,並使用 clear() 方法清除了物件儲存中的所有當前資料。有關完整的可用示例,請參閱我們的 待辦事項通知 應用(檢視即時示例)。
js
// 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;
// Clear all the data from the object store
clearData();
};
function clearData() {
// open a read/write db transaction, ready for clearing the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of the transaction completing, when everything is done
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
`Transaction not opened due to error: ${transaction.error}`;
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// Make a request to clear all the data out of the object store
const objectStoreRequest = objectStore.clear();
objectStoreRequest.onsuccess = (event) => {
// report the success of our request
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
}
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-clear③ |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。