我正在尝试使用 index.openCursor(keyRange.only 或 keyRange.bound 此处提供) 使用使用autoIncrement: true创建的表上的索引访问一个或多个记录。我尝试了多种变体,但没有成功。有人可以使用以下代码作为模板向我展示一个工作示例:
window.indexedDB = window.indexedDB || window.webkitIndexedDB
|| window.mozIndexedDB || window.msIndexedDB;
var ixDb;
var ixDbIndexTest = function () {
//Open or create the requested IndexedDB Database
var ixDbRequest = window.indexedDB.open("testDBindexes", 2);
ixDbRequest.onupgradeneeded = function (e) {
ixDb = ixDbRequest.result || e.currentTarget.result;
objectStore =
ixDb.createObjectStore("demoOS",
{ keyPath: "id", autoIncrement: true });
objectStore.createIndex("ixdemo", "Field1",
{ unique: false, multiEntry: false });
//define new dummy record
var newRecord = {};
newRecord.Field1 = "222";
newRecord.Field2 = "333";
newRecord.Field3 = "444";
var request = objectStore.add(newRecord);
request.onsuccess = function (e) {
var index = objectStore.index('ixdemo');
var range = IDBKeyRange.only("222");
var cursorRequest = index.openCursor(range);
cursorRequest.onsuccess = function(e) {
var cursor = cursorRequest.result || e.result;
alert(cursor.value);
cursor.continue();
}
}
};
};
window.onload = ixDbIndexTest;
更新: 我修改了演示脚本以在 Firefox 和仍然使用 setVersion 的旧 Chrome 版本中工作。但是,您需要为 Chrome 添加额外的版本检查逻辑,因为每次脚本运行时当前逻辑都会运行 setVersion。
window.indexedDB = window.indexedDB || window.webkitIndexedDB
|| window.mozIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction
|| window.mozIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.mozIDBKeyRange || window.msIDBKeyRange;
var ixDb;
var ixDbIndexTest = function () {
//Open or create the requested IndexedDB Database
var ixDbRequest = window.indexedDB.open("testDBindexes", 1);
ixDbRequest.onsuccess = function(e) {
ixDb = ixDbRequest.result || e.currentTarget.result;
if (typeof ixDb.setVersion === "function") {
ixDbVersionRequest = ixDb.setVersion(1);
ixDbVersionRequest.onsuccess = function (e) {
indexTest();
};
}
else {
ixDbRequest.onupgradeneeded = function (e) {
indexTest();
};
}
}
};
window.onload = ixDbIndexTest;
function indexTest() {
var objectStore = ixDb.createObjectStore("demoOS",
{ keyPath: "id", autoIncrement: true });
objectStore.createIndex("ixdemo", "Field1",
{ unique: false, multiEntry: false });
//define new record with users input
var newRecord = {};
newRecord.Field1 = "222";
newRecord.Field2 = "333";
newRecord.Field3 = "444";
var request = objectStore.add(newRecord);
request.onsuccess = function (e) {
var index = objectStore.index('ixdemo');
var range = IDBKeyRange.only("222");
var cursorRequest = index.openCursor();
cursorRequest.onsuccess = function(e) {
var cursor = cursorRequest.result || e.result;
if(cursor) {
alert(JSON.stringify(cursor.value));
cursor.continue();
}
}
}
}