用js,如何通过value获得options的index编号

例如:
<select>
<option value="0">音乐</option>
<option value="1">电影</option>
<select>
我想通过1来获得第二项的index编号,然后将状态改为 selected,请问该怎么写?
不是这个意思啊,我是说通过value的值来改变选择状态,如果第二项的value值为10该怎么选择第二项呢?

通过value获得options的index编号的思路:获取所有option选项数组→循环判断value属性→取得满足要求的option的index值。如果获取options的index编号的目的是为了将其设置为选中项,那么可以有更简单的方式——直接将select对象的value属性值设置为需要选中项的value值即可。实例演示如下:

1、HTML结构

<select id="test">
<option value="0">option-0</option>
<option value="1">option-1</option>
<option value="2">option-2</option>
<option value="3">option-3</option>
<select><br>
选中项value:<input type="text" id="val"><input type="button" value="确定" onclick="fun()">

2、javascript代码

function fun(){
var val = document.getElementById("val").value;
var select = document.getElementById("test");  // 获取select对象
select.value = val; // 设置选中项
// 下面获取目标value值的option的index值
index = 0;
for(i=0;i<select.length;i++){
if(select[i].value == val){
index = i;
break;
}
}
alert(index);
}

3、效果演示

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-11-16
<script language="javascript">
function getValue(){
alert(document.getElementById('selectId').selectedIndex);
document.getElementById('selectId').selectedIndex=1;

}
</script>

<select id="selectId" onchange="getValue()">/**触发事件***/
<option value="0">音乐</option>
<option value="1">电影</option>
</select>本回答被提问者采纳
第2个回答  2007-11-26
<select id="selectId">
<option value="0">音乐</option>
<option value="1">电影</option>
<select>
<script language="javascript">
alert(document.getElementById('selectId').selectedIndex);
document.getElementById('selectId').selectedIndex=1;
</script>
第3个回答  2007-11-26
楼上的,是不是写错了啊
document.getElementById('selectId').seletedIndex=1
第4个回答  2007-11-26
直接设<select>的value为1就行了
oSelect.value="1" //oSelect为<select>标签的id

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网