使用jQuery切换单选按钮 [英] Toggling Radio Buttons with jQuery
本文介绍了使用jQuery切换单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用jQuery切换几个单选按钮。但事实证明并非如此简单。
I am trying to toggle a couple of radio buttons using jQuery. But it is turning out to be not so simple.
<button id="toggler">click me</button><br>
<input type="radio" name="speeds" value="fast" checked>fast<br>
<input type="radio" name="speeds" value="slow">slow<br>
$('#toggler').click(function() {
$('input[name="speeds"]').each(function(){
$(this).prop("checked", !$(this).prop("checked"));
});
});
有谁可以解释为什么上面的代码不起作用?
Could anyone please explain why the code above does not work?
推荐答案
如果只有两个单选按钮
$('#toggler').click(function() {
$('input[type="radio"]').not(':checked').prop("checked", true);
});
演示:小提琴
如果有超过2个元素
var $radios = $('input[type="radio"][name="speeds"]')
$('#toggler').click(function() {
var $checked = $radios.filter(':checked');
var $next = $radios.eq($radios.index($checked) + 1);
if(!$next.length){
$next = $radios.first();
}
$next.prop("checked", true);
});
演示:小提琴
这篇关于使用jQuery切换单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文