[英]Set attribute selected of particular option of select box using jquery
I have a select box with following options 我有一个带有以下选项的选择框
select id="box" ><br/>
option value="1"Same Day<br/>
option value="5">96<br/>
option value="4">72<br/>
option value="3">48<br/>
option value="2">24<br/>
select>
I Want to add attr selected to option value '4' , i know i can show it selected via 我想将选择的attr添加到选项值'4',我知道我可以通过显示它来选择它
$("#box").val(4)
But this just shows it selected but does not add attribute selected to option 4, what i want is to add attribute selected to option. 但这只是显示它已选中,但没有将选中的属性添加到选项4,我想要的是将选中的属性添加到选项。
Please suggest 请建议
Thanks 谢谢
$('#box').children('option:eq(3)').attr('selected', 'selected');
That makes usage of the eq()
selector which querys the index you specify. 这样就可以使用
eq()
选择器查询您指定的索引。
Slightly faster (even if it's more typing) would be the method .eq()
instead of the selector: .eq()
方法而不是选择器会稍微快一点(即使输入更多)。
$('#box').children('option').eq(3).attr('selected', 'selected');
Since .eq()
uses array slices
instead of query'ing over Sizzle. 由于
.eq()
使用array slices
而不是通过Sizzle查询。 As you notice correctly, both versions start indexing at zero. 如您所知,这两个版本都从零开始索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.