如何使用jQuery将check attr添加到单选按钮nth-child?

时间:2013-03-11 08:08:10

标签: jquery radio-button

我有一组单选按钮,我想将check attr添加到其中一个。 这是我的代码:

<input type="radio" name="radioButton" id="rd1">
<input type="radio" name="radioButton" id="rd2">
<input type="radio" name="radioButton" id="rd3">
<input type="radio" name="radioButton" id="rd4">
<input type="radio" name="radioButton" id="rd5">

<script>
   $('input[name=slider]:nth-child(3)').prop('checked', true);
</script>

我用.attr('checked','checked')测试了脚本。 但脚本不正常。我的错了什么?

5 个答案:

答案 0 :(得分:5)

尝试:

$('input[name=radioButton]:eq(2)').prop('checked', true);

答案 1 :(得分:4)

$('input[name=radioButton]:nth-child(3)').attr('checked', true);

$('input[name=radioButton]:nth-child(3)').attr('checked', 'checked');

以下是jsFiddle

答案 2 :(得分:0)

试试这个:

<script>
   $('input[name=radioButton]:nth-child(3)').attr('checked', 'checked');
</script>

答案 3 :(得分:0)

试试这段代码。 使用attr而不是prop。

 $('input[name=slider]:nth-child(3)').attr('checked', true);

答案 4 :(得分:0)

<input type="radio" name="radioButton" value="hello" id="rd1">

您可以添加属性并使用此属性:

$('input [name =“ radioButton”] [ value =“ hello”]')。prop('checked',true);

注意:如果在某些浏览器中有多个单选按钮,并且它们具有不同的组,则“ nth-child”可能会导致某些浏览器出现问题。