我有一个带有一排的HTML表,并且有几个TR会动态添加。每个TR在最后一列中都有一个按钮。

我需要什么,以便通过单击按钮从表中删除最接近的TR?我尝试使用 $(this).closest.remove() 但这无效,所以我认为我需要在这里添加ID或其他内容。

一个基本的示例表看起来如下:

<table class='tableClass'>
    <tbody>
        <th>
            <td>Text</td><td>Text</td><td>Text</td>
        </th>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
    </tbody>
</table>
有帮助吗?

解决方案

你需要给 closest 功能选择器。尝试这个:

$('.btnClass').click(function() {
    $(this).closest('tr').remove();
});

另外,您的HTML无效 th 应该是一个孩子 tr:

<table class='tableClass'>
    <tbody>
        <tr>
            <th>Text</th>
            <th>Text</th>
            <th>Text</th>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
    </tbody>
</table>

示例小提琴

其他提示

您可以使用 .closest( selector ) 适当喜欢:

$(this).closest('tr').remove();

实际上在您的代码中:

$(this).closest.remove()
            ___^___

您缺少开口和关闭的括号 () 和选择器 tr.

http://jsfiddle.net/cpvh9/

$(".btnClass").click(function(){
        $(this).parents('tr').remove();
    });

从您的html代码中,看起来您想删除父tr,请尝试一下

$(".btnClass").click(function(){
    $(this).parents("tr:first").remove();
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top