【问题标题】:how to add class to the last two TRs and apply style to the TDs inside those TRs如何将类添加到最后两个 TR 并将样式应用于这些 TR 内的 TD
【发布时间】:2013-03-15 05:44:15
【问题描述】:

我正在尝试 1)在页面上每个表的最后两个TR添加一个类 2) 并设置这两个 TR 的第 1、2、5 和 8 个 TD。

下面的代码似乎不起作用。

  var rowCount = $('table tr').length;
$('table tr').eq(rowCount - 1).addClass('myClass');
$('table tr').eq(rowCount - 2).addClass('myClass');

谢谢

BB

【问题讨论】:

    标签: jquery


    【解决方案1】:

    要将类添加到每个表的最后两行,您可以使用:

    $('table').each(function () {
        $(this).find('tr').last().addClass('red').prev().addClass('red');
    });
    

    并将一个类添加到每个表的最后两行以及您要使用的每一行的特定列:

    $('table').each(function () {
        $(this).find('tr').last().addClass('myClass')
        .find(':nth-child(1)').addClass('myClass').parent()
        .find(':nth-child(2)').addClass('myClass').parent()
        .find(':nth-child(5)').addClass('myClass').parent()
        .find(':nth-child(8)').addClass('myClass').parent()
        .prev().addClass('myClass')
        .find(':nth-child(1)').addClass('myClass').parent()
        .find(':nth-child(2)').addClass('myClass').parent()
        .find(':nth-child(5)').addClass('myClass').parent()
        .find(':nth-child(8)').addClass('myClass').parent();
    });
    

    最后一点似乎有点乱。我认为有更好的方法可以做到这一点,但这很有效。

    【讨论】:

    • 这是我发现的: $('table tr:last-child td:nth-child(1)').css('background-color', '#ffa');更改页面上每个表格的最后一个 TR 的第一个 td 的颜色。但是, $('table tr:last-child').addClass('myClass');行不通。我试过你的代码仍然不会添加类。
    【解决方案2】:

    试试切片?

    $(function() {
        $('table tr').slice(-2).addClass('last_two');
    
        $('table tr').eq(0).addClass('first')
               .end().eq(1).addClass('second')
               .end().eq(4).addClass('fifth')
               .end().eq(7).addClass('eight');
    });
    

    【讨论】:

    • 嗯,它是一个ID,还是不是??
    • @BumbleBee - 我编辑了答案,还记得文档准备功能吗?
    • @adeneo 在 end() 之前添加到缺少的. :)
    • @wirey - 谢谢,哎呀!错过了?
    • 我试过你的代码,但没有运气。这是我观察到的: $('table tr:last-child td:nth-child(1)').css('background-color', '#ffa');改变每张桌子最后一个 TR 的第一个 td 的颜色。但是, $('table tr:last-child').addClass('myClass');行不通。
    猜你喜欢
    • 2014-08-19
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2023-03-27
    • 2013-03-01
    • 1970-01-01
    • 2010-10-31
    相关资源
    最近更新 更多