IDBRequest: success 事件

IDBRequest 成功时,会触发 success 事件。在 success 事件处理程序中,您可以访问请求的结果,并向同一事务发出更多请求。

此事件不可取消且不会冒泡。

语法

在诸如 addEventListener() 之类的 方法中使用事件名称,或设置事件处理程序属性。

js
addEventListener("success", (event) => {});

onsuccess = (event) => {};

事件类型

一个通用的 Event.

示例

此示例尝试打开一个数据库并使用 addEventListener() 监听 success 事件

js
// Open the database
const openRequest = window.indexedDB.open("toDoList", 4);

openRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = () => {
    console.log("Error creating database");
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

openRequest.addEventListener("success", (event) => {
  console.log("Database opened successfully!");
});

同一个示例,但使用 onsuccess 事件处理程序属性

js
// Open the database
const openRequest = window.indexedDB.open("toDoList", 4);

openRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = () => {
    console.log("Error creating database");
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain
  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
};

openRequest.onsuccess = (event) => {
  console.log("Database opened successfully!");
};

浏览器兼容性

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

另请参阅