【问题标题】:Unchecking radio buttons with jQuery a little buggy使用 jQuery 取消选中单选按钮有点错误
【发布时间】:2025-12-07 13:00:01
【问题描述】:

我需要能够取消选中一组 3 个中选中的单选按钮。它在大多数情况下都有效,但它有点问题 - 有时当我想检查不同的按钮时取消选中,有时不选中当我取消选中另一个按钮时,第一次单击按钮,单击不同的收音机几次后取消选中,等等。希望有人可以看看是什么原因造成的

CSS:

input[type="radio"] {   display: none;  }
input[type="radio"] + label {
    color:#f2f2f2;
    font-family:Arial, sans-serif;
    font-size:14px;
}
input[type="radio"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(../images/check_radio_sheet.png) -38px top no-repeat;
    cursor:pointer;
}
input[type="radio"]:checked + label span {
    background:url(../images/check_radio_sheet.png) -57px top no-repeat;
}

HTML:

<form class="optionsfilter" action="#">
<ul style="list-style: none;">
<li>
<span style="color: #eee;">Smoking Inside?</span>
<div class="clear"></div>
<input type="radio" name="smokingoption" id="smoking" value="smoking"><label for="smoking" onclick=""><span></span>Yes</label>
<input type="radio" name="smokingoption" id="non-smoking" value="non-smoking"><label for="non-smoking" onclick=""><span></span>No</label>
<input type="radio" name="smokingoption" id="cigarsmoking" value="cigar"><label for="cigarsmoking" onclick=""><span></span>Cigars</label>
</li>
</ul>
</form>

这是脚本:

$('input[type="radio"]').click(function() {
    var checked = $(this).attr('checked');
    if(checked){
        $(this).attr('checked', false);
    } else{
        $(this).attr('checked', true);
    }
});

这是一个包含所有代码的 jsFiddle: http://jsfiddle.net/RfDk6/

【问题讨论】:

  • 检查这个。 jsfiddle.net/RfDk6/2
  • 你想达到什么目的?这不是单选按钮的默认行为吗?
  • @DON 仅提供单选按钮的默认行为。我将这些用作过滤器中的一个选项,但我希望用户能够完全取消选中以从过滤器中删除该选项,如果他们愿意的话。由于这三个一起出现,我需要使用单选按钮而不是复选框。
  • @insertusernamehere,我发布的代码取消选中选中的单选按钮,没有选中任何一个。正如我在问题中所说,它有问题,我需要它按预期运行,但我看不出是什么导致了不需要的行为

标签: jquery radio-button


【解决方案1】:

我不知道你想要实现什么,但是从 jQuery 1.6 开始,用于修改表单元素的选中属性,应该使用 prop 方法而不是 attrchecked 是一个属性和设置通过 attr 的 false/true 不会更改单选按钮的 checked 属性。

$('input[type="radio"]').change(function() {
    $(this).prop('checked', function(i, checked){
       return !checked;
    });
});

【讨论】:

    【解决方案2】:

    这适用于 Chrome(我没有在其他地方测试过 - 抱歉)。

    $("input:radio").removeAttr("checked");
    

    .prop 函数只删除了无线电组的第一个实例,而 removeattr 核弹了很多。

    【讨论】: