html中的select元素的option值的获取和其他元素不同,主要表现在select值的获取必须在众多的option中选择,没有其他元素那么直观。
select的相关属性获取说的通俗点就是它的各个option的属性的获取(它的各个option是采用数组存储的),因此获取了它的option,其他的操作就很方便了,和text,button的操作一样。
option的获取方式采用以下方式:
document.getElemtById("selectID").option[index];
其中,selectID是需要操作的select的id,index是select下的option在数组中的下标,通过以下例子可以明白
这样,option的value和option中的显示值就很轻松的获取了,如:
value的获取为 document.getElemtById("selectID").option[index].value;
option中值的获取为 document.getElemtById("selectID").option[index].innerText;
select中初始化的默认option更改为 document.getElemtById("selectID").option[index].setAttribute("selected",true);
这里举一个具体的例子说明一下,具体代码如下:
// --></mce:script>
<body>
<input type="button" name="testOption" value="test" onclick="testOption()">
<hr>
<select name="test2" id="test2">
<option value="111" selected>before_selected</option>
<option value="112">test12</option>
<option value="113">after_selected</option>
</select>
</body>
</HTML>
该例子用来实现一个点击test按钮,显示option value=“112”的value值,并修改select默认option(由before_selected变为after_selected)的功能。