如果选中复选框,则显示或隐藏表行

Dun*_*Luk 4 html javascript checkbox jquery show-hide

我想在选中复选框时隐藏表行(内部带有输入字段)。我发现了一些可行的方法:

的HTML

<table>
    <tr id="row">
        <td><input type="text"></td>
        <td><input type="text"></td>
    </tr>
    <tr>
        <td><input type="checkbox" id="checkbox">Hide inputs</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

脚本

$(document).ready(function () {
    $('#checkbox').change(function () {
        if (!this.checked) 
            $('#row').fadeIn('slow');
        else 
            $('#row').fadeOut('slow');
    });
});
Run Code Online (Sandbox Code Playgroud)

小提琴

但这仅在尚未选中复选框的情况下有效。因此,如果在开始时选中了该复选框,则我希望隐藏表行。我该怎么做呢?

请注意,我对JavaScript不太了解,但我确实需要这个

Moh*_*deh 5

附加事件后触发.change()事件:

$(function () {
    $('#checkbox1, #checkbox2').change(function () {
        var row = $(this).closest('tr').prev();

        if (!this.checked)
            row.fadeIn('slow');
        else 
            row.fadeOut('slow');

    }).change();
});
Run Code Online (Sandbox Code Playgroud)

注意:我使代码更短。

jsfiddle