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

问题描述 投票:3回答:5

我有一组单选按钮,我想将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')测试了脚本。但脚本不正常。我错了什么?

jquery radio-button
5个回答
4
投票
$('input[name=radioButton]:nth-child(3)').attr('checked', true);

要么

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

这是jsFiddle


5
投票

尝试:

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

0
投票

试试这个:

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

0
投票

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

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

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

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

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

注意:如果您在使用其他组之前有多个单选按钮,则“nth-child”可能会在某些浏览器中出现问题。

© www.soinside.com 2019 - 2024. All rights reserved.