选择框脚本
选择框是通过<select>和<option>元素创建的
HTMLSelectElement提供的属性和方法
>add(newOption,relOption):向控件中插入新<option>元素,其位置在相关项之前 >multiple:布尔值,表示是否允许多项选择,等价于html中的multiple特性 >options:控件中所有<option>元素的 HTMLCollection >remove(index):移除给定位置的选项。 >selectedIndex:基于0的选项中的索引,如果没有选中项,其值为-1。对于支持多项的控件,只保存选中项第一项的索引. >size:选择框中可见的行数;等价于HTML中的size 特性
HTMLOptionElement对象的属性有
index:当前选项在options集合中的索引 label:当前选项的标签;等价于HTML中的label特性 selected:布尔值,表示当前选项是否被选中。将这个属性设置为true可以选中当前选项 text:选项的文本 value:选项的值(等价于HTML中的value特性)
读取选择框中的信息
html代码
<form action="" name=""> <select name="location"> <option value="a">a</option> </select> </form>
js代码
var selectbox=document.forms[0].elements["location"];//document.forms[0]获取form,根据elements属性获取到name值为location的字段,即select
//获取到HTMLSelectElement
推荐方法
var txt=selectbox.options[0].text;//选项的文本 var value=selectbox.options[0].value;//选项的值
常规的dom方法
var txt=selectbox.options[0].firstChild.nodeValue;//选项的文本 var value=selectbox.options[0].getAttribute("value");//选项的值
推荐方法效率比常规方法更高,关于它的change事件,只要选中了就会触发
对于只允许选择一项的选择框,访问选择框中项的最简单方式,就是使用选择框的selectedIndex属性
var selectedOption=selectbox.options[selectbox.selectedIndex];
获取选择框中选项的信息
var form = document.forms[0]; var selectbox = form.elements["location"]; var selectedOption = selectbox.options[selectbox.selectedIndex]; var selectIndex = selectbox.selectedIndex; console.log("Selected index:" + selectIndex + "\n Selected text:" + selectedOption.text + "\n Selected value:" + selectedOption.value); //"Selected index:0 Selected text:a Selected value:a"
选择框添加选项
最佳方案
规定这个方法接收2个参数:要添加的新选项和将位于新选项之后的选项。如果想在列表的最后添加一个选项,可以将第二个参数设置为undefined.
var option=new Option("key","value"); selectbox.add(option,undefined); //或者可以用dom的insertBefore()方法,添加到指定项
选择框删除选项
接收一个参数,要移除选项的索引。
selectbox.remove(0);//移除第一个选项
清除选择框中所有的项
function clearSelectbox(selectbox){ for(var i=0,len=selectbox.options.length;i<len;i++){ selectbox.remove(0); } }
这个函数每次只删除选择框的第一个选项,由于移除第一个选项后,所有后续选项都会自动向上移动一个位置。因此会重复移除第一个选项就可以删除所有项了