jQuery设置选择索引 [英] jQuery Set Select Index
问题描述
我有一个选择框:
<select id="selectBox">
<option value="0">Number 0</option>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
<option value="4">Number 4</option>
<option value="5">Number 5</option>
<option value="6">Number 6</option>
<option value="7">Number 7</option>
</select>
我想根据其选定索引将其中一个选项设置为选定".
I'd like to set one of the options as "selected" based on it's selected index.
例如,如果我尝试设置数字3",则尝试这样做:
For example, if I am trying to set "Number 3", I'm trying this:
$('#selectBox')[3].attr('selected', 'selected');
但这不起作用.如何使用jQuery根据选项的索引将其设置为选中状态?
But this doesn't work. How can I set an option as selected based on it's index using jQuery?
谢谢!
推荐答案
注意:答案取决于jQuery 1.6.1 +
NOTE: answer is dependent upon jQuery 1.6.1+
$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true); // To select via value
感谢您的评论,.get
将不起作用,因为它返回的是DOM元素,而不是jQuery元素.请记住,.eq
函数也可以在选择器之外使用.
Thanks for the comment, .get
won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq
function can be used outside of the selector as well if you prefer.
$('#selectBox option').eq(3).prop('selected', true);
如果要使用 value ,也可以更加简洁/可读,而不是依赖于选择特定的 index :
You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:
$("#selectBox").val("3");
注意: .val(3)
在此示例中也很好,但是非数字值必须是字符串,因此我选择了一个字符串以保持一致性.
(例如<option value="hello">Number3</option>
要求您使用.val("hello")
)
Note: .val(3)
works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option>
requires you to use .val("hello")
)
这篇关于jQuery设置选择索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!