单击复选框后显示/隐藏表格行

show / hide table rows after clicking on checkbox

本文关键字:隐藏 表格 显示 复选框 单击      更新时间:2023-09-26

我想在用户单击复选框后删除所有表行,除了带有复选框的表行,并在再次取消选中复选框时显示回表行。我的代码只用于删除,但我需要在取消检查后再次显示该表。

function Showhidefunc(btndel) {
  if (typeof(btndel) == "object") {
    $('table tr td:first-child :checkbox:not(:checked)').closest('tr').remove();
  } else {
      return false;
  }
}
<thead>
<tr>
   <th>Select</th>
   <th>Month</th>
   <th>Username</th>
   <th>Deduction</th>
</tr>
</thead>
<tbody>
<tr>
  <td><input type="checkbox" onChange="Showhidefunc(this);"></td>
  <td><?php echo $Name_row ['Month'];?></td>
  <td><?php echo $Name_row ['Username'];?></td>
  <td><?php echo $Name_row ['Total_Deduction'];?></td>
</tr>
</tbody>

谢谢各位:)

不要对行使用.remove(),因为这会删除它们;一旦你把它们移走,它们就不见了,你再也找不回来了。

先使用.hide(),然后使用.show()

function Showhidefunc(chkbox) {
    if ($(chkbox).is(":checked"))
        $('table tr td:first-child :checkbox:not(:checked)').closest('tr').hide();
    } else {
        $('table tr td:first-child :checkbox:not(:checked)').closest('tr').show();
    }
  }

更新:更新代码以匹配html和更好的if/else

带切换的版本:

function Showhidefunc(chkbox) {
    $('table tr td:first-child :checkbox:not(:checked)').closest('tr').toggle(!$(chkbox).is(":checked"));
  }

顺便说一句,还有其他方法可以做到这一点,例如使用.map()

function Showhidefunc(btndel) { if (typeof(btndel) == "object") { $('table tr td:first-child :checkbox:not(:checked)').closest('tr').remove(); } else { return false; } }

删除应该是.hide()

在其他情况下,您希望执行相同的操作,但使用.show()而不是