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

标签 javascript jquery

我想在用户单击复选框后删除所有表行(带有复选框本身的表行除外),并在再次取消选中该复选框时显示表行。我的代码仅适用于删除,但我需要在取消选中它后再次显示该表。

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

带有 toggle 的版本:

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

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

关于javascript - 单击复选框后显示/隐藏表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38695268/

相关文章:

javascript - 如果找到/返回有效的 JSON,则禁用带有 jQ​​uery 单击事件的 href 链接

php - 如何使用 jQuery DatePicker 设置结束日期从开始日期加一

javascript - 使用 jQuery 将具有特定类的每个 div 的名称保存到变量

javascript - 如何获取包含特定文本的输入标签的数量?

javascript - 在 JQuery 中设置 $(this).text 的样式

javascript - 获取要在 div 中显示的默认值

php - jQuery 文件上传不起作用 : PHP jQuery - correct dependancies missing

javascript:页面加载之前的时间

javascript - 当路径应用程序更改时如何停止滚动事件?

javascript - jQuery - 如何检查 AJAX 调用中响应对象的大小?