Javascript 使用jQuery切换单选按钮

Javascript 使用jQuery切换单选按钮,javascript,jquery,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> $('#toggle

我正在尝试使用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"));
    });
});
点击我
快速

$('#toggler')。单击(函数(){ $('input[name=“speeds”]”)。每个(函数(){ $(this.prop(“选中”),!$(this.prop(“选中”); }); });


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

如果只有两个单选按钮

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

如果有两个以上的元素

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);
});
演示:

组中的单选按钮(即具有相同
名称
值的
输入
s)已经是互斥的。您只需修改一个组的“选中”状态即可更改整个组的状态:

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

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