gpt4 book ai didi

javascript - 选中/取消选中单选按钮

转载 作者:行者123 更新时间:2023-11-30 14:00:47 37 4
gpt4 key购买 nike

$("input[type='radio']").each(function() {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">

我的方法是首先检查我的输入是否为 :checked,如果是,则放置一些具有背景颜色的 CSS 类。我做到了这一点,接下来我要做的是在用户单击单选按钮或任何其他(更好的)想法时删除 :checked 。提交表单后,此代码检查输入是否为 :checked,问题是当我想选择另一个单选按钮时,我得到如下内容:

a busy cat

1和2单选按钮被选中,应该只有2个:checked

最佳答案

您需要添加 else 来移除蓝色,例如:

$("input[type='radio']").each(function () {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}else{
$(this).css('background', 'white');
}
});

您还可以为这些 radio 附加点击事件,例如:

$("body").on("click", "input[type='radio']", function () {
$("input[type='radio']").css('background', 'white');
$(this).css('background', 'blue');
});

关于javascript - 选中/取消选中单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340451/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com