jQuery jQuery删除最后一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7221421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:33:32  来源:igfitidea点击:

jQuery remove last table column

jqueryhtml-table

提问by Oscar Carballal

I currently have a table that can be N columns and N rows. In the interface I have a button to remove the last column, but I can't figure out how to remove the last tdfrom all the rows, what I've achieved so far is to remove the first row tdand the last row td, but leave the others there.

我目前有一个可以是 N 列和 N 行的表。在界面中,我有一个删除最后一列的按钮,但我不知道如何td从所有行中删除最后一列,到目前为止我所取得的成就是删除第一行td和最后一行td,但离开那里的其他人。

Here is my code (only deletes the last title currently):

这是我的代码(目前只删除最后一个标题):

function removeTableColumn() {
    /*
        removeTableColumn() - Deletes the last column (all the last TDs).
    */
    $('#tableID thead tr th:last').remove(); // Deletes the last title
    $('#tableID tbody tr').each(function() {
        $(this).remove('td:last'); // Should delete the last td for each row, but it doesn't work
    });
}

Am I missing something?

我错过了什么吗?

回答by Frédéric Hamidi

That's because the :lastselector only matches the last element in the set.

这是因为:last选择器只匹配集合中的最后一个元素。

You might be looking for :last-child, which matches the elements that are the last child of their parent:

您可能正在寻找:last-child,它匹配作为其父元素的最后一个子元素的元素:

$("#tableID th:last-child, #tableID td:last-child").remove();

回答by Arnaud Le Blanc

:lastreturns the last element found by the selector. So #tableID tr td:lastwould return only one td.

:last返回选择器找到的最后一个元素。所以#tableID tr td:last只会返回一个td

You can select the last td of each tr be doing this:

您可以选择每个 tr 的最后一个 td 这样做:

$('#tableID tr').find('th:last, td:last').remove();

回答by dnxit

You can remove any column from a table like this

您可以像这样从表中删除任何列

    //remove the 1st column
     $('#table').find('td,th').first().remove();

    //remove the 1st column
    $('table tr').find('td:eq(1),th:eq(1)').remove();

   //remove the 2nd column
   $('table tr').find('td:eq(1),th:eq(1)').remove();

   //remove the nth column
   $('table tr').find('td:eq(n),th:eq(n)').remove();

for reference

参考