jQuery - 循环访问子元素

时间:2010-05-19 11:08:56

标签: jquery children

我在表格中有一系列选择框,如下所示:

<tr>
<td><select></select></td>
<td><select></select></td>
<td><select></select></td>
<td><select></select></td>
</tr>

大约10行。

我正在尝试将行中的所有选择框重置为默认值,但是语法有问题,任何人都可以帮忙吗?这就是我现在所拥有的,但它似乎没有起作用:

$(row).children('td > select').each().val('0');

任何建议表示赞赏。

感谢。

2 个答案:

答案 0 :(得分:1)

如果您只是想选择一个默认值,这应该有效(未经测试):

$('select', row).each(function() {
    this.selectedIndex = 0; //or whatever the index you want
});

使用$('select',row)比你的选择器快一点,所以直接访问objects属性,而不是使用jQuery对象。

答案 1 :(得分:0)

您根本不需要each,jQuery会将更改应用于所有匹配的元素:

$(row).children('td > select').val('0');

请注意,它会设置选择框的,例如,选择匹配的value选项。这与设置所选选项的索引不同(此处的另一个答案显示了如何执行此操作)。使用具有非数字值的示例可使区别更清晰:

HTML:

<div id='characters'>
<select name='favorite'>
<option value='fred'>Fred Flintstone</option>
<option value='barney'>Barney Rubble</option>
<option value='wilma'>Wilma Flintstone</option>
<option value='betty' selected>Betty Rubble</option>
</select>
<select name='secondchoice'>
<option value='fred'>Fred Flintstone</option>
<option value='barney selected'>Barney Rubble</option>
<option value='wilma'>Wilma Flintstone</option>
<option value='betty'>Betty Rubble</option>
</select>

jQuery调用将这两者改为'wilma':

$('#characters select').val('wilma');

...或(或许更明智地针对特定的示例)根本没有选择任何选项:

$('#characters select').val('');