html表根据值设置一些单元格文本颜色 [英] html table set some cell text colours based on value

查看:100
本文介绍了html表根据值设置一些单元格文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html表,并且在特定的列中,文本设置为"Y"或"N".我想知道是否可以在加载时以编程方式将文本的颜色设置为Red(红色)?

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

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

推荐答案

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

注意:我测试了上面的文件,它可以工作.复制到您的桌面,另存为yn.html,然后在浏览器中运行.

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

使用纯选择器而不依赖if语句...

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

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

这是泰勒·霍利安(Tyler Holien)的回答.这将是更好的方法,因为它不涉及太多的函数调用,并且在更少的代码中更具表现力.注意:不幸的是,如果还有其他内容可能包含N且不应选择,则不要使用此版本,因为contains将选择其中包含N的所有文本,而不仅仅是"N"文本.

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.

这篇关于html表根据值设置一些单元格文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆