2012-07-03 22 views
2

我知道我可以做设置选择指数

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

选择在选择框中选择一个选项,但我怎么能做到这一点,通过返回的jQuery对象?例如像

var box = $('#selectBox'); 
$(box :nth-child(4)').attr('selected', 'selected'); 
+0

的可能重复的[jQuery的:在选择一个元件已被选择的元素中](http://stackoverflow.com/questions/629730/jquery-selecting-an-element-in-inside-an-already - 选择元素) –

回答

4

您可以使用children

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

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

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

re:'.prop' vs'.attr' - 's/can/should /' – Alnitak

+0

@Alnitak我更喜欢'prop',但是谁知道什么更适合OP。 – VisioN

+0

如果他在1.6+然后恕我直言'.prop'永远是“更好” – Alnitak

0

您可以用类似环境中使用的选择:

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

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

$('#selectBox').val(the_value); 
0
box.find(':nth-child(4)')[0].selected = true; 
+0

你的意思是'prop(“选择”,true)'? – VisioN

+0

@VisioN不,但我的意思是提取DOM节点,你的评论提醒我要修复:) – Alnitak

0

你可能想使用prop()为。

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