【问题标题】:Getting all tr with a particular background-color using selector使用选择器获取具有特定背景颜色的所有 tr
【发布时间】:2014-10-07 23:52:36
【问题描述】:

我有一张有很多行的表。有些行具有特殊的颜色,我想使用 jquery 获取该 tr 元素的数组。我使用了选择器,但没有用

$("#tbodySample").children("tr[background-color='rgb(79,79,79)']").length;

$("#tbodySample").children("tr[style='background-color:rgb(79,79,79)']").length;

$("#tbodySample").children("tr[style='{background-color:rgb(79,79,79)}']").length;

$("#tbodySample").children("tr[background-color='#4F4F4F']").length;

$("#tbodySample").children("tr[style='background-color:#4F4F4F']").length;

$("#tbodySample").children("tr[style='{background-color:#4F4F4F}']").length;

我的html是

<table>
<tbody id="tbodySample">
<tr class="selectable" style="background-color: rgb(79, 79, 79);">contents</tr>
<tr class="selectable" style="background-color: rgb(52, 52, 52);">contents</tr>
<tr class="selectable" style="background-color: rgb(52, 52, 52);">contents</tr>
<tr class="selectable" style="background-color: rgb(52, 52, 52);">contents</tr>
<tr class="selectable" style="background-color: rgb(79, 79, 79);">contents</tr>
.
.
.
</tbody>
</table>

以上所有语句都返回 0。 有没有可靠的方法来实现这一点?

【问题讨论】:

  • 使用 css 类分配颜色,然后找到具有特定类的元素。让生活更轻松。

标签: jquery html jquery-selectors html-table


【解决方案1】:

您可以使用过滤器来检查背景颜色。我正在检查 .css('color') 与十六进制值和 rgb 值的跨浏览器兼容性:

var count = $('#tbodySample').find('tr').filter(function(){
    var colors = ["#4F4F4F","rgb(79, 79, 79)"];
    return $.inArray($(this).css('background-color'), colors) !== -1;
}).length;

JSFiddle

注意:您的 HTML 无效,&lt;td&gt; 元素必须是直接子元素或&lt;tr&gt; 元素

【讨论】:

  • 每个 tr 有 5 个 tds 我这里没有给出
  • 没问题。很高兴能帮上忙。
  • 不起作用的可能原因是什么。样式属性不能用选择器选择吗??
  • 应该可以,但是您在属性选择器中提供的字符串必须完全与实际属性中的值相同(包括空格),即' t 理想,因为 CSS 允许在许多地方使用空白,并且您的属性可能不一致。 jsfiddle.net/gz7xw0vo/2
  • 好的。如果是这样,请告诉我问题中提供的语句中哪个是正确的语法
【解决方案2】:

试试这个:

$("#tbodySample tr[style*='background-color: rgb(79, 79, 79);']").length

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 1970-01-01
    • 2022-01-12
    • 2016-12-05
    • 2021-12-19
    • 2021-05-04
    • 2018-10-13
    • 2017-11-17
    相关资源
    最近更新 更多