我正在尝试使用JavaScript中的箭头键循环显示自定义自动填充选项列表。我试图通过迭代选项并添加一个"选择"来尝试这样做。当前所选选项的ID。我遇到了一个问题,尽管选择了""当前选择的选项的ID是可见的(如果您将其注销,则可以看到ID),ID无法访问(尝试注销element.id将返回一个空字符串)。
以下是代码:
SearchBox.prototype.handleOptionNavigation = function() {
_this.inputElement.addEventListener("keyup", function(event) {
var options = _this.getOptions();
if (event.key === "ArrowUp") _this.moveSelectedUp();
if (event.key === "ArrowDown") _this.moveSelectedDown();
});
}
SearchBox.prototype.getOptions = function() {
return Array.from(document.getElementsByClassName("result-item"));
}
SearchBox.prototype.getSelectedIndex = function() { //here is the problem
var options = _this.getOptions();
if (options.length === 0) return;
console.log(options[2]);
//this returns <li class="result-item" id="selected">...</li>
console.log(options[2].id);
//this returns an empty string
return 1;
//this function is supposed to return the index of the element currently selected;
//I am returning 1 just to see a selected element on the screen.
}
SearchBox.prototype.moveSelectedDown = function() {
var options = _this.getOptions();
if (options.length === 0) return;
var selectedIndex = _this.getSelectedIndex();
if (selectedIndex === -1) {
options[0].id = "selected"
} else if (selectedIndex === (_this.maxResults - 1)) {
options[0].id = "selected"
options[options.length - 1].removeAttribute("id");
} else {
console.log("we are moving down");
options[selectedIndex + 1].id = "selected";
options[selectedIndex].removeAttribute("id");
}
}
SearchBox.prototype.moveSelectedUp = function() {
var options = _this.getOptions();
if (options.length === 0) return;
var selectedIndex = _this.getSelectedIndex();
console.log(selectedIndex);
if (selectedIndex === -1) {
options[options.length - 1].id = "selected";
} else if (selectedIndex === 0) {
options[0].removeAttribute("id");
} else {
options[selectedIndex - 1].id = "selected";
options[selectedIndex].removeAttribute("id");
}
}
这个想法是,每按一次向上或向下箭头,完整选项列表中的不同元素将突出显示。但是,因为我似乎无法访问所选元素的ID,所以它会卡住并且moveSelectedUp / moveSelectedDown函数无法正常工作。
有谁知道这里发生了什么?
谢谢!
答案 0 :(得分:0)
不太确定你在方法SearchBox.prototype.getSelectedIndex
中想要实现的目标,但总是返回1,这应该如何帮助?
我已经更新了你的方法,以便它返回真正的索引,它似乎工作正常,请看下面的小提琴: