使用 jQuery 切换单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19141911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:17:11  来源:igfitidea点击:

Toggling Radio Buttons with jQuery

javascriptjquery

提问by ktm5124

I am trying to toggle a couple of radio buttons using jQuery. But it is turning out to be not so simple.

我正在尝试使用 jQuery 切换几个单选按钮。但事实证明并非如此简单。

<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"));
    });
});

http://jsfiddle.net/beC7q/

http://jsfiddle.net/beC7q/

Could anyone please explain why the code above does not work?

谁能解释一下为什么上面的代码不起作用?

回答by Arun P Johny

If there are only two radio buttons

如果只有两个单选按钮

$('#toggler').click(function() {
    $('input[type="radio"]').not(':checked').prop("checked", true);
});

Demo: Fiddle

演示:小提琴

If there are more than 2 elements

如果有超过 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);
});

Demo: Fiddle

演示:小提琴

回答by André Dion

Radio buttons in a group (i.e., inputs with the same namevalue) are already mutually exclusive. You only need to modify the "checked" state of one to change the entire group's state:

组中的单选按钮(即input具有相同name值的s )已经是互斥的。你只需要修改一个的“checked”状态就可以改变整个组的状态:

This code, for example, would always set the last radio in the group to "checked":

例如,此代码将始终将组中的最后一个收音机设置为“已检查”:

$('#toggler').click(function() {
    $('input[type="radio"][name="speeds"]').last().prop('checked', true);
});

DEMO

DEMO