【问题标题】:How to change the selectIndex of a selectBox in an HTMLCollection?如何更改 HTMLCollection 中选择框的选定索引?
【发布时间】:2018-02-03 20:05:05
【问题描述】:

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

我已经通过var selectBoxes = document.getElementsByClassName("selectBox"); 获得了一个 HTMLCollection 的 selectBoxes 我现在想将每个 selectBoxes 的 selectIndex 更改为 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,这似乎解释了我的部分问题。

【问题讨论】:

    标签: javascript drop-down-menu htmlcollection


    【解决方案1】:

    我错误地访问了 selectedIndex 属性。它不是 selectBox 本身的直接属性,而是似乎在 selectBox 的子项中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多