Red*_*wan 3 javascript drop-down-menu
我的aspx页面上有下拉列表.我想手动设置下拉列表中存在的选定值.这个值我得到的变量.我希望在页面初始化时将此值设置为选定值.我想在javascript中使用它.ddp.SelectedValue ='40'是否有任何下拉属性..?这里我不知道列表中的40的索引.
selectedIndex 是HTMLSelectElement的属性,因此您可以执行以下操作:
<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1; // Selects option "One"
</script>
Run Code Online (Sandbox Code Playgroud)
在给定OPTION元素的情况下,您可以使用index属性获取其索引:
<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index); // alerts "1"
</script>
Run Code Online (Sandbox Code Playgroud)
我想手动设置所选的值
迭代select的选项列表以获得option您感兴趣并设置selected它:
var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
if (options[i].value==='40') {
options[i].selected= true;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
这将选择具有匹配值的第一个选项.如果您有多个具有相同值的选项或多选,则可能需要不同的逻辑.
这个:
document.getElementById('ddp').value= '40';
Run Code Online (Sandbox Code Playgroud)
由HTML5指定做同样的事情,并且已经在大多数现代浏览器中工作了很长时间,但在IE中仍然失败(不幸的是IE9).