这包括上一个问题“IndexedDB Fuzzy Search”中的示例代码。 如何将光标结果绑定(bind)到输入框以创建自动完成效果,并在选择结果时使用 objectStore 中的不同值填充表单的多个输入框?我想在没有任何库的情况下执行此操作。
HTML 输入框。
<input name="name" id="name"> //search by name, when a name is selected the last name and age are automatically attached to the other input boxes
<input name="lastname" id="lastname">
<input name="age" id="age">
Javascript。
var result = [];
db.transaction(['table'], IDBTransaction.READ_ONLY)
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'),
IDBCursor.PREV)
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
result.push([cursor.value.column1, cursor.value.sortcolumn]);
cursor.continue();
} else {
if (result.length) {
result.sort(function (a, b) {
return a[1] - b[2];
});
}
// Process code here
}
};
最佳答案
好吧,在你的情况下,你可能只想要游标返回的第一个结果,所以你只需要检查是否有返回的结果,如下所示:
<input name="name" id="name">
<input name="lastname" id="lastname">
<input name="age" id="age">
<script>
document.getElementById('name').oninput = function () {
var searchTerm = this.value;
var result = [];
db.transaction(['table'], IDBTransaction.READ_ONLY)
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part
IDBCursor.PREV)
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
// Here I assume that your table with 'lastname' and 'age'
// Return result to "lastname" input
document.getElementById('lastname').value = cursor.value.lastname;
// Return result to "age" input
document.getElementById('lastname').value = cursor.value.age;
}
};
}
</script>
关于javascript - 如何将indexedDB游标结果绑定(bind)到自动完成输入框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12729187/