倒数第二的第n个孩子没有'对我来说不起作用

nth child for second last doesn't work in my case

本文关键字:对我来说 不起作用 孩子 倒数第二      更新时间:2023-09-26

我有一个表,我在下面几行做,第一行可以,但第二行不行。我想要的是删除最后一个和倒数第二个td。

$('.table td:last-child').remove()
$('.table td:nth-child(1)').remove()

删除最后一个子项后,倒数第二个子项将成为最后一个子。只需写入

$('.table td:last-child').remove()
$('.table td:last-child').remove()

一句话替代

$('.table td:last-child, .table td:nth-last-child(2)').remove()

:nth-last-child从最后一个元素开始计数,因此:nth-last-chld(2)是倒数第二个

您可以使用以下内容:

$(".table td:nth-last-child(-n+2)").remove();

$(function(){
    $(".table td:nth-last-child(-n+2)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table" border="1">
    <tr>
        <td>TD #0</td>
        <td>TD #1</td>
        <td>TD #2</td>
        <td>TD #3</td>
        <td>TD #4</td>
        <td>TD #5</td>
    </tr>
    <tr>
        <td>TD #1</td>
        <td>TD #2</td>
        <td>TD #3</td>
    </tr>
    <tr>
        <td>TD #1</td>
        <td>TD #2</td>
        <td>TD #3</td>
    </tr>
</table>