2015-12-08 153 views
3

我有一个单选按钮组,我想选择所选按钮之一。从选定的单选按钮中选择下一个单选按钮

$(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>

这是我有,但它是不工作

回答

4

代码的变化是,你不必触发click来检查radio,而不是你可以用.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>

+0

难道你不觉得'.prop('checked',true)'比'.click()'更好吗? – Rayon

+0

@RayonDabre是的,没错。应该是,而不是点击。 – Jai

+0

太好了,谢谢你的解释! – chiapa

4

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

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

next()刚刚得到紧随其后的兄弟姐妹。

在树中的下一个元素是标签,所以你需要使用下一个()两次获得下一个单选按钮

+0

@psylogic完成,感谢不downvoting :) – gurvinder372

+0

我不会因为你给合适的解决方案:)但是我现在没有给予好评! –

+0

不错,我认为它会选择下一个类似的元素。谢谢 – chiapa