【问题标题】:How to highlight certain table rows using jQuery?如何使用 jQuery 突出显示某些表格行?
【发布时间】:2017-09-14 05:52:10
【问题描述】:

我的代码笔: http://codepen.io/leongaban/pen/nJzcv

所以我发现 this great example 在 CSS-Tricks 上突出显示表格行。 (Demo)

但是我不想突出显示我的top row,我尝试仅针对具有类名的某些 td,但仍然没有关闭:(

你会怎么做?

//Row Highlighting
$("table .active").delegate('td','mouseover mouseout', function(e) {
        if (e.type == 'mouseover') {
            console.log('hovering over row');
            $(this).parent().addClass("gray-rollover");
        }
        else {
            $(this).parent().removeClass("gray-rollover");
        }
    });

// Works but highlights all Rows
/*$("table").delegate('td','mouseover mouseout', function(e) {
        if (e.type == 'mouseover') {
            console.log('hovering over row');
            $(this).parent().addClass("gray-rollover");
        }
        else {
            $(this).parent().removeClass("gray-rollover");
        }
    });*/

【问题讨论】:

    标签: jquery html-table row mouseover


    【解决方案1】:

    您可以在第一行周围添加 table head,在其余部分周围添加表格正文:

    <table cellpadding="12" cellspacing="1" border="1">
      <thead><tr>
        <th>Icon</th>
        <th class="data-td data-name">Name</th>
        <th class="data-td data-career">Career</th>
        <th class="data-td data-company">Company</th>
      </tr></thead>
      <tbody><tr>
      <!-- more stuff -->
      </tr></tbody>
    </table>
    

    然后你可以用你的 JavaScript 来定位表格主体:

    $("table > tbody .active").on('mouseover mouseout','td', function(e) {
    

    虽然可以只使用 JS 而无需更改 HTML,但在这种情况下,我更喜欢 HTML 更改,因为它在语义上是正确的——你的第一行不是内容,所以它应该无论如何都要单独标记为标题。

    【讨论】:

      【解决方案2】:

      一种方法是使用not() 选择器:

      $(this).parent().not('tr:first-child').addClass("gray-rollover");
      

      这会将类添加到除鼠标悬停的第一行之外的所有行。

      CodePen here.

      【讨论】:

        【解决方案3】:

        为什么不简单地使用 CSS:

        tr:nth-child(even) td {
            background: #333;
            color: #fff;
        }
        

        所以你想要鼠标悬停的样式,除了第一行。那么:

        tr:hover td {
            background: #333;
            color: #fff;
        }
        
        tr:first-child:hover td{
            background: none;
            color: #333
        }
        

        或者我在这里遗漏了什么?

        【讨论】:

        • 你看过他试图复制的演示吗?
        • @Blazemonger:看起来 OP 只想突出显示行。这可以通过 CSS 实现
        猜你喜欢
        • 2013-10-18
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        相关资源
        最近更新 更多