值
指定索引名称的字符串。
异常
尝试更改索引的名称时,可能会发生几种异常。
InvalidStateErrorDOMException-
如果索引或其对象存储已被删除,或者当前事务不是升级事务,则会抛出此异常。您只能在升级事务期间重命名索引;也就是说,当模式为
"versionchange"时。 TransactionInactiveErrorDOMException-
如果当前事务未激活,则会抛出此异常。
ConstraintErrorDOMException-
如果索引已在使用指定的
name,则会抛出此异常。
示例
在以下示例中,我们打开一个事务和一个对象存储,然后从简单的联系人数据库中获取索引 lName。然后,我们使用 IDBIndex.openCursor() 在索引上打开一个基本游标 — 这与使用 openCursor() 直接在 IDBObjectStore 上打开游标的工作方式相同,不同之处在于返回的记录是根据索引排序的,而不是主键。
索引的名称将记录到控制台:它应返回为 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.name);
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-name① |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。