有没有更好的方法使用 jquery 将组中的最后一个单选按钮设置为 'checked'?

Is there a better way to use jquery to set the last radio button in a group to 'checked'?

是否有更好或更优选的方法来使用 jQuery 自动 select 一组中的最后一个单选按钮(有 4 个按钮)?

$(':radio[name=filter_option]:nth(3)').prop('checked', true);

这有效,只是好奇这是否合适?

我找到了一个简单的解决方案

 <div class="test1_active">
      <input type='radio' name='radio1' class='radioButton' />
      <input type='radio' name='radio1' class='radioButton' />
      <input type='radio' name='radio1' class='radioButton' />        
      <input type='radio' name='radio1' class='radioButton' />
    </div>

<script>
    $('.radioButton').last().prop('checked', true);
</script>

享受 jsfiddle link https://jsfiddle.net/dupinderdhiman/cjh7bqdL/

干杯

这当然是对的。如果可以添加更多单选按钮 - 但您知道您总是想要最后一项 selected - 您可以使用 last:

$(':radio[name=filter_option]').last().prop('checked', true);

... 或者,如果您始终知道您想要的商品的价值 select(不考虑顺序):

$(':radio[value=third]').prop('checked', true);

... 或者,也许您可​​以在输入标签中包含一个 class 或其他一些属性来区分它。即:

$(':radio.autoselect').prop('checked', true);