从选定的单选按钮中选择下一个单选按钮

Selecting next radio button from selected one

本文关键字:单选按钮 下一个 选择      更新时间:2023-09-26

我有一个单选按钮组,我想选择所选按钮旁边的一个。

$(document).ready(function() {
  $('.next').click(function() {
    $("input[name=choice]:checked").next().click();
  });
});
.button {
  display: inline-block;
  padding: 1em;
  margin: 20px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="choise_1" name="choice" checked="checked" />
<label for="choise_1">One</label>
<input type="radio" id="choise_2" name="choice" />
<label for="choise_2">Two</label>
<input type="radio" id="choise_3" name="choice" />
<label for="choise_3">Three</label>
<div class="button next">SELECT NEXT</div>

这就是我所拥有的,但它不起作用

代码中的更改是,您不必触发click来检查radios,而是可以使用.prop()方法更改属性checked

您需要.nextAll(':radio:first'):

描述:获取匹配元素集中每个元素的所有以下同级元素,可选地由选择器进行筛选

.nextAll(filter)中,使用这种方法,您不必担心您的设计是否发生了更改或在列表中添加了另一个元素。它将始终只针对:radio,直到它共享同一个父级为止。

$(document).ready(function() {
  $('.next').click(function() {
    $("input[name=choice]:checked").nextAll(':radio:first').prop('checked', true);
  });
});
.button {
  display: inline-block;
  padding: 1em;
  margin: 20px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="choise_1" name="choice" checked="checked" />
<label for="choise_1">One</label>
<input type="radio" id="choise_2" name="choice" />
<label for="choise_2">Two</label>
<input type="radio" id="choise_3" name="choice" />
<label for="choise_3">Three</label>
<div class="button next">SELECT NEXT</div>

试试这个fiddle(只需确保next()被调用两次,因为两个复选框之间有一个标签)

$('.next').click(function() {
  $("input[name=choice]:checked").next().next().click();
});

next()只获取紧随其后的同级。

树中的下一个元素是标签,因此您需要使用next()两次才能获得下一个单选按钮