我在一个表中创建了一组单选按钮,如下所示
<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>
当单击任何单选按钮时,需要更改parent的背景,并且其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");
}
});
此代码正常工作,当单击无线电时,父母的背景会改变,但当无线电未选中时,父母的背景不会被重置为默认值。我的脚本中有没有什么错误,或者有没有其他的错误?
发布于 2013-09-25 17:59:25
检查这个:http://jsfiddle.net/ChaitanyaMunipalle/R4htK/
首先,你必须重置单选按钮父按钮的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");
});
发布于 2013-09-25 18:08:44
您可以像下面这样优化代码
$(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/
您需要根据您的要求修改颜色代码。
发布于 2013-09-25 18:04:13
问题是您单独绑定到单选按钮,因此单击只发生一次。尝尝这个
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/
https://stackoverflow.com/questions/19001457
复制相似问题