1

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

    <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");
    }
});

此代码正在工作,当单击收音机时,父级的背景会发生变化,但是当取消选中收音机时,父级的背景不会重置为默认值。我的脚本中是否有任何错误或任何其他方式?

4

3 回答 3

2

检查这个: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-25T09:59:25.457 回答
1

您可以像下面这样优化代码

$(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-25T10:08:43.653 回答
0

问题是您分别绑定到单选按钮,因此点击只发生一次。尝试这个

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/

于 2013-09-25T10:04:12.917 回答