在 jQuery 中单击时选中复选框<tr>



我有以下HTML代码:

<table class="table table-striped">
    <thead>
        <tr>
            <th></th>
            <th>Color</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="checkbox checkbox-primary">
                    <input type="checkbox" name="elements_ids">
                    <label></label>
                </div>
            </td>
            <td>Blue</td>
        </tr>
        ...
    </tbody>
</table>

如何使用 jQuery,如果我单击<tr>,我可以选中复选框,但前提是该复选框<tr>有一个复选框要检查。我不希望此代码影响我页面上的所有表格。

我试过了:

$(".table tbody tr").has(':checkbox').change(function(e){
    alert('ee');
});

此外,如果选中该复选框,我该如何恢复?

你能帮忙吗?

它的点击事件中找到tr复选框,然后使用如下所示prop()方法设置复选框状态。

$(".table tbody tr").click(function(e) {
    if($(e.target).is(':checkbox')) return; //ignore when click on the checkbox
  
    var $cb = $(this).find(':checkbox');
    $cb.prop('checked', !$cb.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
    <thead>
        <tr>
            <th></th>
            <th>Color</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="checkbox checkbox-primary">
                    <input type="checkbox" name="elements_ids">
                    <label></label>
                </div>
            </td>
            <td>Blue</td>
        </tr>
    </tbody>
</table>

有一个 jsfiddle

以及你需要的javascript:

$("tr").on("click", function(e){
    $("input[type='checkbox']", this).each( function() {
        $(this).attr('checked', !$(this).attr('checked'));
    });
});

这样,它将反转单击行上的所有复选框。

最新更新