$("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,问题是当我想要选择另一个单选按钮时,会得到类似如下的结果:

选择了%1和%2单选按钮,应该只有%2 :checked
发布于 2019-05-28 18:45:03
您需要添加else来移除蓝色,如下所示:
$("input[type='radio']").each(function () {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}else{
$(this).css('background', 'white');
}
});您还可以为这些无线电附加一个单击事件,如下所示:
$("body").on("click", "input[type='radio']", function () {
$("input[type='radio']").css('background', 'white');
$(this).css('background', 'blue');
});发布于 2019-05-28 18:49:41
您的JS的问题在于,您从未从任何未选中的复选框中删除类。还要注意,each()仅在页面加载时运行(假设您没有将其放在事件处理程序中,但问题没有显示),因此您需要在change事件处理程序中运行逻辑:
var $radio = $("input[type='radio']").on('change', function() {
$radio.removeClass('blue');
$(this).toggleClass('blue', this.checked);
});也就是说,您想要做的事情可以通过使用CSS更简单地实现:
input {
visibility: hidden;
}
input:before {
content: '';
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #CCC;
visibility: visible;
}
input:checked:before {
background-color: blue;
}<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">
发布于 2019-05-28 18:58:33
我认为您的代码的问题在于您使用的是each事件,而不是change或click事件。这意味着您正在尝试更改单选按钮的颜色,甚至在用户执行任何操作之前也是如此。阅读以下代码,这将解决提交表单和自定义单选按钮的问题:
$(".radio-button").click(function() {
$(this).addClass("blue-background");
$(this).siblings().removeClass("blue-background");
var radioID = $(this).data('radio');
$('#' + radioID).attr("checked", "checked");
if ($('#' + radioID).siblings(":checked")) {
$('#' + radioID).siblings().removeAttr("checked");
}
});.blue-background {
background-color: blue;
}
input[type='radio'] {
visibility: hidden;
}
.radio-button {
height: 15px;
width: 15px;
margin: 5px;
border-radius: 50%;
display: inline-block;
border: 1px solid black;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="radio" id="radio1" data="cool" name="cool" checked="checked">
<input type="radio" id="radio2" data="cool" name="cool">
<input type="radio" id="radio3" data="cool" name="cool">
<div class="radio-button" data-radio="radio1"></div>
<div class="radio-button" data-radio="radio2"></div>
<div class="radio-button" data-radio="radio3"></div>
</div>
我希望这能对你有所帮助。
https://stackoverflow.com/questions/56340451
复制相似问题