HTML DOM Select 对象


HTML DOM Select 对象

HTML DOM Select 对象代表 HTML Form 表单元素中的选择框。通过 Select 对象,可以访问和操作选择框中的选项和属性。

获取 Select 对象

获取 Select 对象有多种方式,例如通过 document.getElementById 或 document.forms 等方法获取 Form 元素,然后通过其 elements 属性获取 Select 对象。此外,可以通过 document.getElementsByTagName 方法获取所有 Select 元素的 NodeList,再通过遍历获取所需的 Select 对象。

const select1 = document.getElementById("select1")
const select2 = document.forms[0].elements["select2"]
const select3List = document.getElementsByTagName("select")
const select3 = select3List[2]

Select 对象属性

length

length 属性返回 Select 对象中选项的数量。

const select = document.getElementById("select1")
console.log(select.length)

options

options 属性返回 Select 对象的选项列表,是一个 HTMLCollection,可以通过下标或命名方式访问其中的选项元素。

const select = document.getElementById("select1")
const option1 = select.options[0]
const option2 = select.options.namedItem("option2")

selectedIndex

selectedIndex 属性表示当前选择的选项在 options 列表中的下标,如果没有选项被选择则返回 -1。

const select = document.getElementById("select1")
const selectedOption = select.options[select.selectedIndex]

value

value 属性返回当前选择的选项的值。

const select = document.getElementById("select1")
const selectedValue = select.value

Select 对象方法

add(option, before)

add 方法向 Select 对象中添加新的选项,并可指定插入位置。

const select = document.getElementById("select1")
const option = document.createElement("option")
option.value = "option3"
option.text = "Option 3"
select.add(option, 1) // 在第二个选项前插入

remove(index)

remove 方法移除 Select 对象中指定下标的选项。

const select = document.getElementById("select1")
select.remove(2) // 移除第三个选项

blur()

blur 方法使 Select 对象失去焦点。

const select = document.getElementById("select1")
select.blur()

focus()

focus 方法使 Select 对象获取焦点。

const select = document.getElementById("select1")
select.focus()

scrollIntoView()

scrollIntoView 方法将 Select 对象滚动到可见区域。

const select = document.getElementById("select1")
select.scrollIntoView()

Select 事件

onchange

onchange 事件在选择框的值被更改后触发。

const select = document.getElementById("select1")
select.onchange = function() {
  console.log("选中了新的选项")
}

总结

HTML DOM Select 对象是表单元素中的重要组成部分,通过 Select 对象,我们可以对其选项和属性进行访问和操作。同时,Select 对象还提供了多个方法和事件,使其更加灵活和强大。