IDBIndex: getKey() 方法
注意:此功能在 Web Workers 中可用。
IDBIndex 介面的 getKey() 方法返回一個 IDBRequest 物件,並在單獨的執行緒中,查詢與此索引中給定鍵對應的、或者如果 key 設定為 IDBKeyRange 時的第一個匹配的主鍵。
如果找到主鍵,它將設定為請求物件的 result。請注意,這不會像 IDBIndex.get 那樣返回整個記錄。
語法
getKey()
getKey(key)
引數
key可選-
用於標識要檢索的記錄的鍵或
IDBKeyRange。如果此值為 null 或缺失,瀏覽器將使用無界鍵範圍。
返回值
一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。
如果操作成功,請求的 result 屬性的值是與給定鍵或鍵範圍匹配的第一個記錄的鍵。
異常
此方法可能會丟擲以下型別之一的DOMException:
TransactionInactiveErrorDOMException-
如果此
IDBIndex的事務處於非活動狀態,則會丟擲此異常。 DataErrorDOMException-
如果提供的鍵或鍵範圍包含無效鍵,則會丟擲此異常。
InvalidStateErrorDOMException-
如果
IDBIndex已被刪除或移除,則會丟擲此異常。
示例
在以下示例中,我們打開了一個事務和一個物件儲存,然後從一個簡單的聯絡人資料庫中獲取了索引 lName。然後,我們使用 IDBIndex.openCursor 在該索引上打開了一個基本遊標——這與直接在 ObjectStore 上使用 IDBObjectStore.openCursor 開啟遊標的工作方式相同,但返回的記錄是根據索引排序的,而不是主鍵。
然後使用 myIndex.getKey('Bungle') 來檢索 lName 為 Bungle 的記錄的主鍵,並在成功回撥返回時將該請求的結果記錄到控制檯。
最後,我們遍歷每條記錄,並將資料插入 HTML 表中。有關完整的可執行示例,請參閱我們的 IndexedDB-examples demo 倉庫(線上檢視示例)。
function displayDataByIndex() {
tableEntry.textContent = "";
const transaction = db.transaction(["contactsList"], "readonly");
const objectStore = transaction.objectStore("contactsList");
const myIndex = objectStore.index("lName");
const getKeyRequest = myIndex.getKey("Bungle");
getKeyRequest.onsuccess = () => {
console.log(getKeyRequest.result);
};
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-getkey① |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。