html table 根据值设置一些单元格文本颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4880595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:29:09  来源:igfitidea点击:

html table set some cell text colours based on value

htmlhtml-table

提问by Coder 2

I have an html table and in a particular column the text is either set to 'Y' or 'N'. I'm wondering if it is possible to set the colour of the text to Red programmatically on load if the value is'N'?

我有一个 html 表,在特定列中,文本设置为“Y”或“N”。我想知道如果值为“N”,是否可以在加载时以编程方式将文本的颜色设置为红色?

<table>
    <tr>
        <td>N</td>
        <td>Y</td>
    </tr>
</table>

回答by Jared Farrish

Using jQuery, it's easy:

使用jQuery,很容易:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('#table_id td.y_n').each(function(){
        if ($(this).text() == 'N') {
            $(this).css('background-color','#f00');
        }
    });
});

</script>

</head>
<body>

<table id="table_id">
 <tr><th>Question</th><th>Y/N?</th></tr>
 <tr><td>I am me.</td><td class="y_n">Y</td></tr>
 <tr><td>I am him.</td><td class="y_n">N</td></tr>
 <tr><td>I am not sure.</td><td class="y_n">Y</td></tr>
 <tr><td>This is a table.</td><td class="y_n">Y</td></tr>
</table>

</body>
</html>

Note: I tested the above file and it works. Copy to your desktop, save as yn.html, and run in a browser.

注意:我测试了上面的文件并且它有效。复制到桌面,另存为 yn.html,然后在浏览器中运行。

EDIT: To accomplish with a pure selector and not rely on the if statement...

编辑:要使用纯选择器完成而不依赖于 if 语句...

$(document).ready(function(){
    $("#table_id td.y_n:contains('N')").css('background-color','#fcc');
});

This was following Tyler Holien's answer. This would be the better way to do it, since it doesn't involve so many function calls and is more expressive in less code. NOTE: Unfortunately, do not use this version if there would be other content that may contain N's and should not be selected, since contains will select all text that has N in it, not JUST the 'N'-only text.

这是在泰勒霍利恩的回答之后。这将是更好的方法,因为它不涉及这么多的函数调用,并且在更少的代码中更具表现力。注意:不幸的是,如果有其他内容可能包含 N 并且不应选择,请不要使用此版本,因为包含将选择其中包含 N 的所有文本,而不仅仅是“N”文本。

回答by Tyler Holien

Try the following CSS:

尝试以下 CSS:

td[value="N"] {
    color: red;
}

回答by citynorman

This is what I did

这就是我所做的

    $('.dataframe td').each(function(){
        var num = parseFloat($(this).text());
        if (num > 0) {
            $(this).addClass('success');
            //$(this).css('color','Green');
        } else if (num < 0) {
            $(this).addClass('danger');
            //$(this).css('color','Red');
        }
    });