使用jQuery切换单选按钮

ktm*_*124 7 javascript jquery

我正在尝试使用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"));
    });
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/beC7q/

任何人都可以解释为什么上面的代码不起作用?

Aru*_*hny 27

如果只有两个单选按钮

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

演示:小提琴

如果有超过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);
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


And*_*ion 9

组中的单选按钮(即input具有相同name值的s )已经是互斥的.您只需修改一个"已检查"状态即可更改整个组的状态:

例如,此代码始终将组中的最后一个无线电设置为"已选中":

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

DEMO