0

如果选中了全选复选框,我正在尝试向我的 tr 行添加一个类,但我似乎无法让添加类工作(如果已取消选中全部检查,则显然删除它们),我正在使用在每个单独的行上切换以添加/删除类,但似乎无法让它为检查所有工作。

这是我的桌子:

<form>
<table cellspacing="0" cellpadding="0" class="tablesorter" id="table">
  <thead>
    <tr>
      <th valign="middle" align="left" class="filebox"><input type="checkbox" id="checkall" name="checkall"></th>
      <th valign="middle" align="left" class="header filename"><strong>Filename</strong></th>
      <th valign="middle" align="left" class="header filesize"><strong>Size</strong></th>
      <th valign="middle" align="left" class="header filedate"><strong>Date</strong></th>
    </tr>
  </thead>
  <tbody class="file">
    <tr>
      <td valign="middle" align="left" class="filebox"><input type="checkbox" id="checkbox" name="checkbox"></td>
      <td valign="middle" align="left" class="filename">Search48.png</td>
      <td valign="middle" align="left" class="filesize">6 KB</td>
      <td valign="middle" align="left" class="filedate">21/10/2010</td>
    </tr>
    <tr>
      <td valign="middle" align="left" class="filebox"><input type="checkbox" id="checkbox" name="checkbox"></td>
      <td valign="middle" align="left" class="filename">shopping_trolley48.png</td>
      <td valign="middle" align="left" class="filesize">3 KB</td>
      <td valign="middle" align="left" class="filedate">21/10/2010</td>
    </tr>
  </tbody>
</table>
</form>

这是我的jQuery代码:

//check all checkboxes
$("#checkall").click(function () {
  $(this).parents("#table:eq(0)").find(":checkbox").attr("checked", this.checked);
});

//add highlight to tr
$("#checkbox").click(function() {
  $(this).parent().parent().toggleClass("highlight");
});
4

2 回答 2

2

You cant use an ID here since it's repeated, instead use a class like class="checkbox" instead of the id="checkbox", like this:

$("#checkall").change(function () {
  $(this).closest("table").find(":checkbox").attr("checked", this.checked).change();
});

$(".checkbox").change(function() {
  $(this).closest('tr').toggleClass("highlight", this.checked);
});

You can test it out here. Also note the use of change instead of click so the state is correct, the use of closest() to get the nearest parent of that selector, and calling .change() on all the checkboxes you're changing, so their row class gets updated correctly.

于 2010-10-21T21:50:27.923 回答
1

http://beckelman.net/2008/11/18/select-all-checkboxes-in-a-table-column-with-and-without-jquery-plugin-demo/

<script type="text/javascript">
$(document).ready(function() {
    $("#tableOne thead tr th:first input:checkbox").click(function() {
        var checkedStatus = this.checked;
        $("#tableOne tbody tr td:first-child input:checkbox").each(function() {
            this.checked = checkedStatus;
        });
    });

});
</script>
于 2012-04-27T11:02:25.870 回答