【问题标题】:JQUERY Select all td cells that are inside a tr with certain styleJQUERY选择具有特定样式的tr内的所有td单元格
【发布时间】:2013-04-18 14:49:16
【问题描述】:

如何更改具有特定样式的 tr 内的 td 单元格的颜色?

例如:

<tr style="display: table-row">
<td></td>
<td></td>
</tr>

到目前为止我已经这样做了,但它并没有完全起作用:

if ($('.mydiv').css('display') == 'table-row') {
   $(this).siblings('td').css("background-color", "white");
}

【问题讨论】:

  • 我会使用 children() 选择器。 $("tr").children("td").css("blabla") ...

标签: jquery css html-table tablerow


【解决方案1】:

我的第一个想法是:

$('td').filter(function(){
    return this.parentNode.style.display == 'table-row';
}).css('background-color','#fff');

正如所写,这将选择所有td 元素,然后将其过滤到其父tr 具有style="display: table-row;" 的元素;不过,这确实要求 tr 具有内联样式设置。然而,再添加一点 jQuery,您可以通过以下方式实现同​​样的效果:

$('td').filter(function(){
    return $(this).parent().css('display') == 'table-row';
}).css('background-color','#fff');

这将以相同的方式过滤,但包括在外部样式表中设置的 CSS(或在文档的 head 中的 style 标记中)。

但是,我会减少 DOM 遍历并仅显式处理 tr 元素,并使用给定的类名来实现相同的目的:

$('tr').filter(function(){
    return $(this).css('display') == 'table-row';
}).addClass('hasDisplayTableRow');

这当然允许使用 CSS:

tr.hasDisplayTableRow td {
    /* css */
}

【讨论】:

  • 不错,没想到这么多!
【解决方案2】:

你不能为风格做到这一点,你需要一个类:

<tr style="display: table-row" class="myrow">
    <td></td>
    <td></td>
</tr>

然后你可以在css中设置样式:

tr.myrow td{
    background-color: white
}

或者在 jQuery 中:

$("tr.myrow td").css({"background-color": "white"})

编辑大卫的回答表明这是可能的。虽然它很聪明,但类方法更易于维护 IMO

【讨论】:

    【解决方案3】:

    比较内联样式并不总是一个好主意。

    相反,为什么不将类添加到有问题的 tr 中,这样它会更干净。

    .table-row{
       display: table-row;
    }
    

    那你就可以用这个了

    if ($('.mydiv').hasClass('table-row')) {
       $(this).siblings('td').css("background-color", "white");
    }
    

    而不是这个&lt;tr style="display: table-row"&gt;

    尝试更改您的标记

    <tr class="table-row">
    

    【讨论】:

      【解决方案4】:

      为什么不通过 CSS 来实现呢?这是我在 JQuery 中的做法。

      $("tr[style='<your style value here>'] td").css("background-color", "white");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        • 1970-01-01
        • 2015-02-09
        • 2017-09-13
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        相关资源
        最近更新 更多