IDBIndex: keyPath 属性
注意:此功能在 Web Workers 中可用。
IDBIndex 接口的 keyPath 属性会返回当前索引的 键路径。如果为 null,则此索引不会自动填充。
值
可以用作键路径的任何数据类型。
示例
在以下示例中,我们打开了一个事务和一个对象存储,然后从一个简单的联系人数据库中获取了索引 lName。然后,我们使用 IDBIndex.openCursor 在该索引上打开了一个基本游标——这与直接在 ObjectStore 上使用 IDBObjectStore.openCursor 打开游标的工作方式相同,但返回的记录是根据索引排序的,而不是主键。
当前索引的键路径已记录到控制台:它应该作为 lName 返回。
最后,我们遍历每条记录,并将数据插入 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");
console.log(myIndex.keyPath);
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 # dom-idbindex-keypath |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。