5

我的下拉菜单与此非常相似:

<select id='someSelect'>
    <option value="0">---select one---</option>
    <optgroup label="Bikes">
        <option value="B-4">Hayabusa</option>
        <option value="B-2">GSXR</option>
        <option value="B-3">Ninja</option>
        <option value="B-6">Enticer</option>
    </optgroup>
    <optgroup label="Cars"> 
        <option value="C-4">Audi TT</option>
        <option value="C-2">Awesome Car</option>
        <option value="C-23">Japanese car</option>
        <option value="C-9">German car</option>
    </optgroup>
</select>

我只想选择第一组的第一个元素(这里是自行车)。请问我该如何在jQuery中处理它?

目前,我试过这个:

$('#someSelect option:nth-child(1)').attr("selected", "selected");

但是,问题是,因为有三个第一个元素(--select--HayabusaAudi TT它选择了所有三个,最终选择Audi TT

我试图做一些事情each并只选择第二个,但后来我意识到下拉菜单是动态的,我不想选择默认的(即--select one--),而是选择第一组的第一个元素

我试图模拟一个 jsfiddle,但它被搞砸了并且无法正常工作,不知道为什么:-/
你可以在这里看到它

4

7 回答 7

7

是一个示例,这是我使用的选择器:

$("#someSelect optgroup option:first").attr("selected", "selected");

如您所见,我通过查看 optgroup 元素内部来使用第一个选项。

于 2011-08-17T16:56:21.140 回答
4

Well this works:

http://jsfiddle.net/nYd67/1/

$(function(){
    $('#someSelect optgroup:eq(0) option:eq(0)').attr("selected", "selected");
});
于 2011-08-17T16:55:48.187 回答
4

从 optgroup 中选择而不是选择:

$('optgroup[label=Bikes] option:first')

或者,如果您不想指定标签,也只需在 optgroup 上进行过滤:

$('optgroup:first option:first')
于 2011-08-17T16:56:50.453 回答
3

只需在选择器中包含 optgroup:

$('#someSelect optgroup:nth-child(2) option:nth-child(1)')

请记住,:nth-child()选择器是基于 1 的,而不是基于 0 的。此外,在这种情况下,您甚至不需要使用标签名称来限定选择器,因此它也可能只是:

$('#someSelect :nth-child(2) :nth-child(1)')
于 2011-08-17T16:56:30.553 回答
2

I always find that .eq() is a lot easier to use. This seems to work correctly in your jsfiddle.

$('#someSelect option').eq(1).attr("selected", "selected");  
于 2011-08-17T16:55:26.790 回答
2
$('#someSelect optgroup:first option:first').attr('selected', true);

这行得通,我已经在你的 html 上进行了测试

于 2011-08-17T16:59:03.570 回答
1

id 为“someSelect”的第一个元素中option的第一个选择器:optgroupselect

"select#someSelect > optgroup:nth-child(1) > option:nth-child(1)"
于 2011-08-17T16:59:39.577 回答