jQuery删除表列

问题描述 投票:6回答:6

我有一张表,不能更改标记:

<table>
    <thead>
        <tr>
            <th>
                blablabla
            </th>
            <th>
                blablabla
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                efgd
            </td>
            <td>
                efghdh
            </td>
        </tr>
    </tbody>
</table>

这是我的函数,应删除一列。点击单元格即可调用它:

function (menuItem, menu) {
    var colnum = $(this).prevAll("td").length;

    $(this).closest('table').find('thead tr th:eq('+colnum+')').remove();
    $(this).closest("table").find('tbody tr td:eq('+colnum+')').remove();    
    return;
}

但是它会删除其他内容,而不是我要删除的列。我在哪里错了?

jquery
6个回答
14
投票

一列几乎只是单元格,因此您需要手动循环遍历所有行并通过索引删除该单元格。

这应该为您删除第3列提供了一个很好的起点:

$("tr").each(function() {
    $(this).children("td:eq(2)").remove();
});

8
投票

[此方法将.delegate()用于处理程序,更本地化的方法是使用cellIndex获取被单击的单元格索引,并使用cells从每一行中拉出该单元格。

示例: http://jsfiddle.net/zZDKg/1/

$('table').delegate('td,th', 'click', function() {
    var index = this.cellIndex;
    $(this).closest('table').find('tr').each(function() {
        this.removeChild(this.cells[ index ]);
    });
});

8
投票

这对我来说很好:

$(".tableClassName tbody tr").each(function() {
    $(this).find("td:eq(3)").remove();
});

1
投票

如果您有静态html(考虑10列的表格),

然后使用以下命令删除标题的第一列:

 $('#table th:nth-child(1),#table td:nth-child(1)').remove();

现在新表将有9列,现在您可以使用数字删除任何列:

 $('#table th:nth-child(7),#table td:nth-child(7)').remove();

0
投票

从每一行中删除第一列。

$('.mytable').find("tr td:nth-child(1)").each(function(){
    $(this).remove()
});

0
投票

通过在目标列上应用某些类,我们可以将其删除。例如

<tr>
    <td>ID</td>
    <td>Name</td>
    <td><button class="btnRemoveMember">X</button></td>
</tr>

从上面的示例表中,我们可以删除表的第3列,如下所示。

$(.btnRemoveMember).closest('td').remove();
© www.soinside.com 2019 - 2024. All rights reserved.