如何通过选择元素的ID设置选择元素的选择选项? [英] How to set selected option of select element by its ID?
问题描述
<select id="comboBox">
<option id="1">One</option>
<option id="2">Two</option>
<option id="3">Three</option>
<option id="4">Four</option>
</select>
我想选择ID为3的选项.有什么办法可以不循环地进行操作?我希望这样的事情
I want to select option with ID 3. Is there any way how to do it without loop? I expect something like this
$("#comboBox").val("3");
,但用ID代替值.(所以我的意思是作为comboBox的成员访问该选项,而不是通过像 document.getElementById('3');
这样的选择器来访问)
but with ID instead of value. (So I mean to access that option as member of comboBox, not through selector like document.getElementById('3');
)
推荐答案
<script type="text/javascript">
document.getElementById("3").selected=true;
</script>
或
<script type="text/javascript">
document.getElementById("comboBox").options[2].selected=true;
</script>
或
<script type="text/javascript">
document.getElementById("comboBox").selectedIndex=2;
</script>
或
<script type="text/javascript">
document.getElementById("comboBox").options.namedItem("3").selected=true;
</script>
对于最后一个,请参见 https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#namedItem()和 http://www.w3schools.com/jsref/coll_select_options.asp
For the last one see https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#namedItem() and http://www.w3schools.com/jsref/coll_select_options.asp
您可以跳过对较短的 document.getElementById("comboBox").namedItem("3").selected = true;
这篇关于如何通过选择元素的ID设置选择元素的选择选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!