javascript - 用于选择表中所有行的复选框

标签 javascript jquery html checkbox

我的 table 里面有一张 table 。基本结构如下

<input type="checkbox" name="CheckAll" id="CheckAll"/> <b>Click to select all Option Values</b>
<table class="Parent">
  <tr>
     <td><input type="checkbox" id="Parent">Parent1</td>
     <td><table class="Children">
        <tr><td><input type="checkbox" id="Child">Child1</td></tr>  
        <tr><td><input type="checkbox" id="Child">Child2</td></tr>
        <tr><td><input type="checkbox" id="Child">Child3</td></tr>
     <td>
  </tr>
  <tr>
     <td><input type="checkbox" id="Parent">Parent2</td>
     <td><table class="Children">
        <tr><td><input type="checkbox" id="Child">Child1</td></tr>  
        <tr><td><input type="checkbox" id="Child">Child2</td></tr>
     <td>
  </tr>

当我单击“全部选中”(表格上方的复选框)时,我希望选中或取消选中所有复选框。我用以下方法做了

    $(document).ready(function () {
        $("#CheckAll").change(function () {
            $("input:checkbox").prop('checked', $(this).prop("checked"));
        });
    });

现在,当选择其中一个父级时,我尝试选择所有子级。假设我无权访问 View 中的父 ID。如何仅访问与正在更改的复选框相邻的表格?

最佳答案

您可以通过定位下一个 TD,然后它包含的表来实现这一点。
请注意,您必须将 #Parent#Child 等更改为类,因为您不能有重复的 ID。

$('.Parent[type=checkbox]').on('change', function() {
    $(this).closest('td')
           .next('td')
           .find('table input[type=checkbox]')
           .prop('checked', this.checked);
});

关于javascript - 用于选择表中所有行的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35409526/

相关文章:

javascript - 使用JS从输入标签读取多个文件

javascript - 按属性值对对象数组进行排序

jquery - 解析 AJAX 内容中的相关资源

jquery - jquery mobile 中的搜索过滤栏

javascript - Jquery .load 导致按钮点击问题

javascript - 如何在 javascript 中使用 onclick 将数组中的复选框值传递给函数

javascript - 在复选框选择上显示 div

php - 终端中从文件中提取文本的命令是什么

javascript - 在 NestJS 中添加 header HttpRequest

javascript - 实时网站不显示特定的 angularjs 指令(但显示其他指令)