首页 > 解决方案 > 在jQuery中,单击后删除表格中的tr

问题描述

我有这种类型的表:

<tr>
    <td>
        <input type="number">
    </td>
    <td>
        <button type="button" data-action="remove-item">
            <i class="fa fa-trash"></i>
        </button>
    </td>
</tr>

通过单击“删除项目”,我想删除当前的<tr>.

这是我尝试过的:

$('[data-action="remove-item"]').click(function(){
    $(this).closest('td').closest('tr').remove();
})

但有时它不起作用。

为什么 ?

谢谢。

标签: jquery

解决方案


.closest()函数将找到您要删除的元素。所以你不需要使用它两次。

Jquery.com下面介绍了该.closest()功能。

向上移动 DOM 树,直到找到匹配的选择器

$('[data-action="remove-item"]').click(function(){
    $(this).closest('tr').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
    <tr>
        <td>
            <input type="number"> 1
        </td>
        <td>
            <button type="button" data-action="remove-item">
                remove
            </button>
        </td>
    </tr>
    <tr>
        <td>
            <input type="number"> 2
        </td>
        <td>
            <button type="button" data-action="remove-item">
                remove
            </button>
        </td>
    </tr>
    <tr>
        <td>
            <input type="number"> 3
        </td>
        <td>
            <button type="button" data-action="remove-item">
                remove
            </button>
        </td>
    </tr>
</table>


推荐阅读