更改类中每个html select元素的选定选项

时间:2012-07-11 17:21:53

标签: jquery html css

我正在尝试更改一组html选择元素的选定选项。我已经给了他们所有相同的类,以便我可以使用jQuery一次性选择它们,但由于某种原因它只更改了类中的第一个元素。这是一个演示:http://jsfiddle.net/bwhitney/xP4FP/1/

以下是代码:

<select id="config1" class="config">
<option>foo</option>
<option selected>bar</option>
</select>

<select id="config2" class="config">
<option>foo</option>
<option selected>bar</option>
</select>

<select id="config3" class="config">
<option>foo</option>
<option selected>bar</option>
</select>

使用jQuery:

$('.config option:eq(0)').attr('selected', 'selected');​

此代码的结果是只有第一个select元素才会选择foo选项。第二个和第三个仍然会选择bar。我认为使用jQuery选择一个类会选择所有具有该类的项目。有没有办法用一个选择器选择所有这三个?

作为对可能答案的先发制人的回应(我确定某人会考虑建议这样做): 我知道我可以写一个for循环来选择每个$('#config' + i)。如果没有办法一次性选择它们,我将最终做到这一点。

6 个答案:

答案 0 :(得分:3)

尝试使用nth-child

$('select option:nth-child(1)').prop('selected', 'selected');

示例:http://jsfiddle.net/K4mnx/

答案 1 :(得分:3)

而不是

$('.config option:eq(0)').attr('selected', 'selected');​

你必须使用

$('.config option:nth-child(1)').attr('selected', 'selected');​​​​​​​​​​​​​​​​​​

:eq():nth-child()之间的根本区别在于

:当量()

Select the element at index n within the matched set.

首先根据:eq()之前的表达式匹配元素,例如.config option

如果您执行console.log($('.config option'));,则会获得以下

[ <option>​foo​</option>​, <option selected>​bar​</option>​, <option>​foo​</option>​, <option selected>​bar​</option>​, <option>​foo​</option>​, <option selected>​bar​</option> ​]

:eq(0)过滤此匹配集,因此只返回第一个元素,即<option>foo</option>

:第n个孩子()

Selects all elements that are the nth-child of their parent.

使用:nth-child()过滤时会考虑父元素。

以下命令

可以最好地证明这种差异
console.log($('.config option:eq(0)'));

console.log($('.config option:nth-child(1)'));

第一个命令,如预期的那样,返回[<option>​foo​</option>​],因为它是匹配的元素集的第一个元素。

第二个命令,返回

[ <option>​foo​</option>​, <option>​foo​</option>​, <option>​foo​</option>​ ]

因为它会选择.config类型option的所有第一个孩子。

所有其他答案绝对正确。

我只是想加上一些解释。 :)

答案 2 :(得分:1)

尝试使用.each()这个:

$('.config').each(function(index){
    $(this).children('option:eq(0)').attr('selected', 'selected')
});

JSFiddle

答案 3 :(得分:1)

将eq(0)更改为:

$('.config option:first-child').attr('selected', 'selected');​

答案 4 :(得分:0)

也许这个:

$('.config').each(function(){ this.options[0].selected = 'selected'; });

答案 5 :(得分:0)

AFAIK,你只能用循环来做,否则只是更新第一个。 http://jsfiddle.net/xP4FP/2/

$('.config option:eq(0)').each(function(i,el){$(el).attr('selected', 'selected')};