从HTML表中删除选定的行

时间:2015-02-06 19:31:58

标签: javascript jquery html

我正在尝试删除所选行(通过复选框),但我不明白我哪里出错了

这是我的代码

JQuery的

$("#delete").click(function(){
    $("table input[type ='checkbox']:checked").parent().parent().remove();
});

HTML

<div class = "patientData">
    <div class ="searchBar">
        <input type = "search" name = "search" class = "search">
        <a href="#"><i class ="fa fa-search"></i></a>
        <button id = "delete">Delete Selected</button>
    </div>
    <table style ="width:95%" class = "Info">
        <tr>
            <th><input type="checkbox" id="select"> </th>
            <th> Name</th>
            <th>Number</th>
            <th>Date</th>
        </tr>
    </table>
</div>

用户输入行,这就是为什么我的表默认只有标题。我现在已经坚持了一段时间没有研究帮助我解决问题。

如果有人可以帮助,请提前致谢。

1 个答案:

答案 0 :(得分:0)

您应该使用:has选择器来获取包含复选框的所有行,而不是回到父级。这将使选择器保持在行级别,从而防止DOM更改意外地占用太多父项并删除页面的大块。

类似的东西:

$("#delete-button").on("click", function(e) {
  $("#delete-table tr:has(td > input[type=checkbox]:checked)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="delete-button">Delete!</button>
<table id="delete-table">
  <tr>
    <th>
      <input type="checkbox" />
    </th>
    <th>Header</th>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Row 3</td>
  </tr>
</table>

相关问题