IDBIndex: openCursor() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

openCursor() 方法是 IDBIndex 介面的一個方法,它返回一個 IDBRequest 物件,並在單獨的執行緒中,建立一個 遊標,用於指定的鍵範圍。

該方法根據指定的方向,將遊標的位置設定為相應的記錄。

如果未指定鍵範圍或鍵範圍為 null,則該範圍包含所有記錄。

語法

js
openCursor()
openCursor(range)
openCursor(range, direction)

引數

range 可選

用於作為遊標範圍的鍵或 IDBKeyRange。如果未傳入任何值,則預設情況下將選擇此物件儲存中的所有記錄的鍵範圍。

direction 可選

遊標的 方向。有關可能的值,請參閱 IDBCursor 常量

返回值

一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。

如果操作成功,請求的 result 屬性的值是

  • 一個指向與給定查詢匹配的第一條記錄的 IDBCursorWithValue 物件
  • 如果未找到匹配的記錄,則為 null

異常

此方法可能會丟擲以下型別之一的DOMException

TransactionInactiveError DOMException

如果此 IDBIndex 的事務處於非活動狀態,則會丟擲此異常。

TypeError

如果 direction 引數的值無效,則會丟擲此異常。

DataError DOMException

如果提供的鍵或鍵範圍包含無效鍵,則會丟擲此異常。

InvalidStateError DOMException

如果 IDBIndex 已被刪除或移除,則會丟擲此異常。

示例

在以下示例中,我們開啟一個事務和一個物件儲存,然後從一個簡單的聯絡人資料庫中獲取索引 `lName`。然後,我們使用 `openCursor()` 在該索引上開啟一個基本遊標 — 這與直接在 `ObjectStore` 上使用 IDBObjectStore.openCursor 開啟遊標的工作方式相同,不同之處在於返回的記錄是根據索引排序的,而不是根據主鍵排序的。

最後,我們遍歷每條記錄,並將資料插入 HTML 表中。有關完整的可執行示例,請參閱我們的 IndexedDB-examples demo 倉庫線上檢視示例)。

js
function displayDataByIndex() {
  tableEntry.textContent = "";
  const transaction = db.transaction(["contactsList"], "readonly");
  const objectStore = transaction.objectStore("contactsList");

  const myIndex = objectStore.index("lName");

  myIndex.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      for (const cell of [
        cursor.value.id,
        cursor.value.lName,
        cursor.value.fName,
        cursor.value.jTitle,
        cursor.value.company,
        cursor.value.eMail,
        cursor.value.phone,
        cursor.value.age,
      ]) {
        const tableCell = document.createElement("td");
        tableCell.textContent = cell;
        tableRow.appendChild(tableCell);
      }
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbindex-opencursor②

瀏覽器相容性

另見