简体   繁体   English

有条件地改变表格行的背景颜色

[英]conditionally change the background-color of table row

I have a table with 2 rows and I want to apply background color to the second row(Specific row).我有一个有 2 行的表,我想将背景颜色应用于第二行(特定行)。 And the second row is displayed conditionally.第二行有条件地显示。 Some pages may have second row and some may not.有些页面可能有第二行,有些可能没有。 I tried to set the background-color using jQuery but it didn't work.我尝试使用 jQuery 设置背景颜色,但没有成功。 Please suggest if that is possible only with css.请建议这是否仅适用于 css。


Code:代码:


<table>
    <tr>
        <td>overload</td>
        <td>one</td>
    </tr>
    <tr>
        <td>workload</td>
        <td>two</td>
    </tr>
    <tr>
        <td>capacity</td>
        <td>three</td>
    </tr>
</table>

Now, I want to apply background-color to the second row.现在,我想将背景颜色应用于第二行。 So, the second row may or may not present all the time.因此,第二行可能会或可能不会一直出现。 If there is no second row, the third row becomes the second row and I don't want background-color to be applied to that row.如果没有第二行,则第三行成为第二行,我不希望将背景颜色应用于该行。

I have tried following with jQuery:我尝试过使用 jQuery:

function applyBGColor() {
    var secondRow = $('table tr:nth-child(2) td:first-of-type').text();
    if(secondRow === 'workload') {
        $('table tr:nth-child(2)').css('background-color', '#f5f5f5')
    }
}

But when I debug it the 'secondRow' variable gets empty string.但是当我调试它时,'secondRow'变量得到空字符串。 But when directly type it in the console like $('table tr:nth-child(2) td:first-of-type').text() this, it gives me the text of the td.但是当像$('table tr:nth-child(2) td:first-of-type').text()这样直接在控制台中输入它时,它会给我 td 的文本。

You shouldn't be checking if row exists based on your text.您不应该根据您的文本检查行是否存在。 Text is easily changeable.文字很容易改变。 Give your second row an id property and access your row with $('#id') .给你的第二行一个 id 属性并使用$('#id')访问你的行。

Something like this:像这样的东西:

<table>
    <tr>
        <td>overload</td>
        <td>one</td>
    </tr>
    <tr id="second-row">
        <td>workload</td>
        <td>two</td>
    </tr>
    <tr>
        <td>capacity</td>
        <td>three</td>
    </tr>
</table>

and then:接着:

function applyBGColor() {
    if($('#second-row').length) {
        $('#second-row').css('background-color', '#f5f5f5')
    }
}

Please call function applyBGColor();请致电 function applyBGColor(); Then check if the HTML然后检查HTML

 applyBGColor(); function applyBGColor(){ var secondRow = $('table tr:nth-child(2)').html(); console.log(secondRow); if(secondRow) { $('table tr:nth-child(2)').css('background-color', '#f5f5f5') } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>overload</td> <td>one</td> </tr> <tr> <td>workload</td> <td>two</td> </tr> <tr> <td>capacity</td> <td>three</td> </tr> </table>

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

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