如何在未选中时重置单选按钮父级的背景

How to reset the background of parent of the radio button when unchecked?

本文关键字:单选按钮 背景      更新时间:2023-09-26

我在表格中创建了一组单选按钮,例如

    <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/