删除表行jquery

时间:2014-09-29 10:07:41

标签: jquery removeall

我有这个表格行

<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er</td>
    <td>
        <button class="btn btn-danger" data-id="1"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er</td>
</tr>
<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er</td>
    <td>
        <button class="btn btn-danger" data-id="2"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er</td>
</tr>
<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er</td>
    <td>
        <button class="btn btn-danger" data-id="3"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er</td>
</tr>

我需要的是当用户点击任何行的删除按钮时,应该删除该行。

1 个答案:

答案 0 :(得分:1)

使用.closest()并找到关于按钮的最近的tr并将其删除,如下所示。

$('.btn.btn-danger').click(function(){
  $(this).closest('tr').remove();  //or  $(this).closest('tr').hide();
});

Fiddle DEMO

OR

$('.btn.btn-danger').click(function(){
  $(this).parent().parent().remove();  //or  $(this).parent().parent().hide();
});

Fiddle DEMO

完整代码: -

&#13;
&#13;
$('.btn.btn-danger').click(function(){
  $(this).closest('tr').remove();  //or  $(this).closest('tr').hide();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er</td>
    <td>
        <button class="btn btn-danger" data-id="1"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er</td>
</tr>
<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er1</td>
    <td>
        <button class="btn btn-danger" data-id="2"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er1</td>
</tr>
<tr role="row" class="even">
    <td class="sorting_1">10</td>
    <td>er2</td>
    <td>
        <button class="btn btn-danger" data-id="3"><i class="fa fa-trash fa-lg"></i> Delete record</button>
    </td>
    <td>er2</td>
</tr>
</table>
&#13;
&#13;
&#13;