IDBTransaction: objectStore() 方法

注意: 此功能在 Web Workers 中可用。

IDBTransaction 接口的 objectStore() 方法返回已添加到此事务作用域的对象存储。

对同一个事务对象使用同一个名称调用此方法时,每次调用都将返回同一个 IDBObjectStore 实例。如果在不同的事务对象上调用此方法,则将返回不同的 IDBObjectStore 实例。

语法

js
objectStore(name)

参数

name

所请求的对象存储的名称。

返回值

用于访问对象存储的 IDBObjectStore 对象。

异常

NotFoundError DOMException

如果请求的对象存储不在此事务的作用域内,则会抛出此异常。

InvalidStateError DOMException

如果请求是在已删除或移除的源对象上发出的,或者事务已结束,则会抛出此异常。

示例

在以下代码片段中,我们在数据库上打开了一个读写事务,并将一些数据添加到对象存储中。此外,还请注意附加到事务事件处理程序的函数,以便在成功或失败的情况下报告事务打开的结果。有关完整的示例,请参阅我们的 待办事项通知 应用程序 (查看示例在线版)。

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①

浏览器兼容性

BCD 表格仅在启用 JavaScript 的浏览器中加载。

另请参阅