繁体   English   中英

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

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

我有一个有 2 行的表,我想将背景颜色应用于第二行(特定行)。 第二行有条件地显示。 有些页面可能有第二行,有些可能没有。 我尝试使用 jQuery 设置背景颜色,但没有成功。 请建议这是否仅适用于 css。


代码:


<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>

现在,我想将背景颜色应用于第二行。 因此,第二行可能会或可能不会一直出现。 如果没有第二行,则第三行成为第二行,我不希望将背景颜色应用于该行。

我尝试过使用 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')
    }
}

但是当我调试它时,'secondRow'变量得到空字符串。 但是当像$('table tr:nth-child(2) td:first-of-type').text()这样直接在控制台中输入它时,它会给我 td 的文本。

您不应该根据您的文本检查行是否存在。 文字很容易改变。 给你的第二行一个 id 属性并使用$('#id')访问你的行。

像这样的东西:

<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>

接着:

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

请致电 function applyBGColor(); 然后检查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