设置选择索引

时间:2012-07-03 10:51:28

标签: jquery

我知道我可以通过

在选择框中选择一个选项
$('#selectBox :nth-child(4)').attr('selected', 'selected');

但是我怎么能通过返回的jQuery对象来做到这一点?例如

之类的东西
var box = $('#selectBox');
$(box  :nth-child(4)').attr('selected', 'selected');

4 个答案:

答案 0 :(得分:4)

您可以使用children

box.children(':nth-child(4)').attr('selected', 'selected');

BTW,从jQuery 1.6开始,您可以使用prop代替attr

box.children(':nth-child(4)').prop('selected', true);

答案 1 :(得分:0)

您可以将选择器与上下文一起使用:

$(':nth-child(4)', box).attr('selected', 'selected');

PS: 如果您知道选项值,则可以使用.val()方法。

$('#selectBox').val(the_value);

答案 2 :(得分:0)

box.find(':nth-child(4)')[0].selected = true;

答案 3 :(得分:0)

您可能希望使用prop()

var box = $('#selectBox');
box.children(':nth-child(4)').prop('selected', 'selected');
相关问题