繁体   English   中英

我们如何使用jquery更改tr的背景颜色?

[英]How can we change the background color of a tr using jquery?

我有一个类名为.myTab的表,

<table class="table table-bordered myTabl">
    <tr style="background:#ff0">
       <td>...</td>
    </tr>
    <tr style="background:#f00">
       <td>...</td>
    </tr>
    <tr style="background:#ff0">
       <td>...</td>
    </tr>
    <tr style="background:#f00">
       <td>...</td>
    </tr>
</table>

现在我想检查是否有任何行

background:#f00;
if ($(".myTabl table tr").css("background-color") == "f00"){
  $(".myTabl table tr").css({"background-color":"ff0"});
}

这个怎么做?

您无需遍历表中的所有行并检查颜色是否为黄色( #ff0 ),而是可以使用以下颜色作为选择器来选择所有黄色行:

$('.table tr[style*="background:#ff0;"]')

然后将匹配元素的背景色更改为红色( #f00 ):

.css({"background-color": "#f00"});

请参见下面的工作示例:

 $('.table tr[style*="background:#ff0;"], .table tr[style*="background:#ffff00;"]').css({ "background-color": "#f00" }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table table-bordered myTabl"> <tr style="background:#ff0;"> <td>...</td> </tr> <tr style="background:#f00;"> <td>...</td> </tr> <tr style="background:#ff0;"> <td>...</td> </tr> <tr style="background:#f00;"> <td>...</td> </tr> <tr style="background:#ffff00;"> <td>...</td> </tr> <tr style="background:#ff00ff;"> <td>...</td> </tr> </table> 

遍历行并在函数中获取tr style属性,然后使用正则表达式查找background十六进制值并进行检查。

 $(".myTabl tr").each(function(){ var match = $(this).attr("style").match(/background\\s*:\\s*#(\\w+)/); if (match != null && match[1] == "f00") $(this).css("background-color", "blue"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table table-bordered myTabl"> <tr style="background:#ff0"> <td>...</td> </tr> <tr style="background:#f00; font-size:12px"> <td>...</td> </tr> <tr style="background:#ff0"> <td>...</td> </tr> <tr style="font-size:12px; background : #f00"> <td>...</td> </tr> </table> 

您的逻辑有几个问题。 首先,您需要遍历所有tr元素并分别进行处理。 您还需要修复您的选择为.myTabl table ,因此额外的table选择不正确。

然后,如果您检查css('background-color')的输出,则会看到它的格式为rgb() ,而不是十六进制或纯色名称。 因此,您需要在if条件下进行测试。 尝试这个:

 $(".myTabl tr").each(function() { if ($(this).css('background-color').toLowerCase() === "rgb(255, 255, 0)") { $(this).css("background-color", "#f00"); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table table-bordered myTabl"> <tr style="background:#ff0"> <td>...</td> </tr> <tr style="background:#f00"> <td>...</td> </tr> <tr style="background:#ff0"> <td>...</td> </tr> <tr style="background:#f00"> <td>...</td> </tr> </table> 

话虽如此,如果您仅使用类来设置颜色,就会简单得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM