单击同一行中的任何复选框时,选中/取消选中表格行中的复选框

She*_*ero 5 javascript checkbox

我有一个简单的表,如下所示,每行的第一列和最后一列都有复选框.

<table style="width:100%">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Jackson</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

问题:当我选中/取消选中第一行中最后一列的复选框时,应检查/取消选中同一行中第一列的复选框.同样,如果我选中/取消选中第一列的复选框,则应选中/取消选中相应的最后一列复选框.

我怎样才能在javascript中实现这一点?任何帮助或指示将非常感激.

这是我创造的小提琴:小提琴

谢谢.

Ray*_*yon 6

使用:checkbox选择器选择输入类型checkbox元素.

试试这个:

$(':checkbox').on('change', function() {
  $(this).closest('tr').find(':checkbox').prop('checked', this.checked);
});
Run Code Online (Sandbox Code Playgroud)
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

使用JavaScript:

使用querySelectorAll('[type="checkbox"]')找到checkbox的元素.

试试这个:

var checkboxes = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(checkboxes, function(checkbox) {
  checkbox.onchange = function() {
    var currentRow = this.parentNode.parentNode;
    var cbElems = currentRow.querySelectorAll('[type="checkbox"]');
    [].forEach.call(cbElems, function(cb) {
      cb.checked = this.checked;
    }.bind(this))
  };
});
Run Code Online (Sandbox Code Playgroud)
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
Run Code Online (Sandbox Code Playgroud)
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)