如何在未选中时重置单选按钮父级的背景
How to reset the background of parent of the radio button when unchecked?
我在表格中创建了一组单选按钮,例如
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" />
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
当单击任何单选按钮时,需要更改父级的背景,并且它的JQuery就像-
$(document).on('click', '#8-9', function (event) {
$checked = $("#8-9").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#ff0000");
$(this).parent().css("color", "#fff");
}
});
$(document).on('click', '#9-10', function (event) {
$checked = $("#9-10").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#252525");
$(this).parent().css("color", "#fff");
}
});
此代码有效,单击收音机时,父级的背景会更改,但是当取消选中收音机时,父级的背景不会重置为默认值。我的脚本中是否有任何错误或任何其他方式
检查这个:http://jsfiddle.net/ChaitanyaMunipalle/R4htK/
首先,您必须重置单选按钮父级的css,然后设置选中的css。
$('input[name=radios]').on('change', function() {
$('input[name=radios]').parent().css("background-color", "#ff0000");
$('input[name=radios]').parent().css("color", "#fff");
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
});
您可以像下面这样优化代码
$(document).on('change', '.radioBtn', function (event) {
$('.radioBtn').parent().css("background-color", "#FFF").css("color", "#000");
$(this).parent().css("background-color", "#000").css("color", "#fff");
});
并像这样修改HTMl,
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" class="radioBtn" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" class="radioBtn"/>
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
检查此 http://jsfiddle.net/8fWZG/1/
您需要根据需要修改颜色代码。
问题是您单独绑定到单选按钮,因此单击仅发生一次。 试试这个
var selected = null;
$(document).on("click", "input[type='radio']", function(){
if(selected != null){
selected.parent().css({backgroundColor:"white", color:"black"});
}
$(this).parent().css({backgroundColor:"black", color:"white"});
selected = $(this);
})
http://jsfiddle.net/ricobano/YBW9c/
相关文章:
- 多个单选按钮组相互干扰
- 是否可以禁用jquery中的单个单选按钮
- Javascript:无法获取变量中的单选按钮值
- 通过ajax到php文件获取单选按钮值
- 互斥单选按钮和相应的输入字段
- 用于选择MVC3中单选按钮值的JavaScript
- 如何获取单选按钮的多个实例的选定单选按钮值
- react testUtils模拟点击单选按钮而不触发onchange
- 单击单选按钮时如何更改背景颜色
- 单选按钮 - 单击时设置背景样式
- JavaScript:取消选择时设置单选按钮的背景(单选按钮组)
- 如何在未选中时重置单选按钮父级的背景
- 单击输入字段将背景颜色应用于父项,并取消选择初始选择的单选按钮
- 根据答案更改单选按钮的背景
- 如果选中单选按钮,则更改父背景颜色
- 单选按钮不改变背景颜色HTML/CSS
- JavaScript -如果选中单选按钮,更改背景颜色
- jQuery onClick 单选按钮背景更改
- 如果未选中,请更改单选按钮的背景颜色
- 使背景像单选按钮一样在打开状态和关闭状态之间切换,当单击它时