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 - 参考示例:待办事项通知(查看实时示例)。