html5-关于select元素的一些你不知道的操作

select元素的常用操作

添加option选项

selectEl:选择框元素
allOptions:选择框的所有选项

1.使用选择框的add()方法

// 将optionA置于newOption之后
selectEl.add(newOption, optionA)
// 将optionA置于选项列尾部(兼容IE)
selectEl.add(newOption, undefined)

2.使用DOM方法

newOption = document.createElement('option')
newOption.appendChild(document.createTextNode('F'))
newOption.setAttribute('value', 'f')
selectEl.appendChild(newOption)

3.使用option构造函数(IE8之前存在问题)

// 第二个参数value值是可选的
newOption = new Option('G', 'g')
selectEl.appendChild(newOption)

4.使用insertBefore()方法,可以将元素插入到指定位置

newOption = new Option('H')
// 选择框中最后一个元素
var lastNode = selectEl.lastChild || allOptions[allOptions.length - 1]
selectEl.insertBefore(newOption, lastNode)

change事件

selectEl.onchange = function (event) {
    var target = event.target
    var curOption = allOptions[target.selectedIndex]
    console.log(`selectedIndex的值:${target.selectedIndex}`)
    console.log(`当前选中项在options集合中的索引:${curOption.index}\n当前选中项的标签:${curOption.label}`)
    console.log(`当前选中项是否被选中:${curOption.selected}`)
    console.log(`选中项的文本:${curOption.text}\n选中项的值:${curOption.value}`)
    console.log(`选中项的下标:${selectEl.selectedIndex}`)
    console.log(`选择框的类型:${selectEl.type}`)
    console.log(`选择框可见的行数:${selectEl.size}`)
}

移除option选项

1.使用DOM的removeChild()方法

selectEl.removeChild(allOptions[0])

2.使用选择框的remove()方法

selectEl.remove(0)

3.使用DOM出现之前的遗留方式

// allOptions[0] = null
selectEl.options[0] = null

猜你喜欢

转载自blog.csdn.net/harmsworth2016/article/details/80444749