2011-10-01 141 views
3

我想自动选择多个单选按钮组的第一个单选按钮。使用jQuery选择多个单选按钮组的第一个单选按钮

<div class="element"> 
<input type="radio" name="group1" value="1"> 
<input type="radio" name="group1" value="2"> 
<input type="radio" name="group1" value="3"> 
</div> 

<div class="element"> 
<input type="radio" name="group2" value="1"> 
<input type="radio" name="group2" value="2"> 
<input type="radio" name="group2" value="3"> 
</div> 

这里的东西,而这个工程:

$('.element').each(function(){ 
    $(this).find('input[type=radio]:first').attr('checked', true); 
}); 

我想不通为什么我不能使它工作使用:使用each()方法第一选择

下面的代码不起作用:它只选择第一个div中的第一个单选按钮,你能告诉我为什么吗?

$('.element input[type=radio]:first').each(function(){ 
    $(this).attr('checked', true); 
}); 

由于

回答

10

第一选择循环遍历每个.element。第二个选择器循环遍历每个仅由一个元素组成的element input[type=radio]:first

我翻译你的代码人类可读的序列:

  1. 选择.element
    通过每.element
    查找无线电输入元素
    设置checked=true第一次出现。
  2. 选择.element的孩子的第一个无线电输入元素。
    循环通过与选择器匹配的每个元素(只有一个)
    设置checked=true


替代方式:

//Alternative method 
$('element').each(function(){ 
    $('input[type=radio]', this).get(0).checked = true; 
}); 

//Another method 
$('element').each(function(){ 
    $('input[type=radio]:first', this).attr('checked', true); 
}); 
+0

所以这意味着我只能使用第一个解决方案来选择每个.element的第一个单选按钮?没有更直接的方式来使用它:第一个选择器? – Vincent

+0

查看我的更新回答。 –

+0

感谢您的非常明确的解释 – Vincent

1

尝试使用第n个孩子:

$('.element').each(function(){ 
    $(this).find('input[type=radio]:nth-child(1)').attr('checked', true); 
}); 
2

最简单的方法是使用:first-child选择。相对于:first,只返回第一个匹配的元素,:first-child将返回这是它的父元素的第一个孩子的任何元素:

//returns the first radio button in group1, and the first one in group2 as well. 
$('.element input[type=radio]:first-child'); 

见罗布·W公司的答案的解释,为什么你的代码ISN”不工作。