如何在 HTML 中更改 selectBox 的选择索引?



我正在尝试重置页面上所有选择框的值。有问题的事件发生在 onClick 中,因此所有内容都加载到 DOM 中。

我已经通过var selectBoxes = document.getElementsByClassName("selectBox");获得了选择框的 HTML 格式,我现在想将每个选择框的选择索引更改为 0。

但是,每次我尝试从 HTMLCollection 访问特定对象的属性时,我最终都会得到一个未定义的值。

selectBoxes.item(0).selectedIndex = undefined selectBoxes[0].selectedIndex = undefined

var selectBoxes = document.getElementsByClassName("filterBox");
console.log(selectBoxes); //a nice JavaScriptObject
for(i = 0; i < selectBoxes.length; i++){
selectBoxes.item(i).selectedIndex = 0;
}

这是一篇关于 HTMLCollections 的非常有趣的文章:https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9 这似乎解释了我的部分问题。

我错误地访问了选定的索引属性。它不是 selectBox 本身的直接属性,而是它似乎在 selectBox 的子项内部。

var selectBoxes = document.getElementsByClassName("filterBox");
for(i = 0; i < selectBoxes.length; i++){
selectBoxes.item(i).children[0].selectedIndex = 0;
}

最新更新