如何改变一个单元格的背景颜色基于其值使用javascript


How to change the background color of a cell based on its value using javascript?

我有一个3列的表:

  • field1是Category
  • field2和field3保持测量值(整数1、2、3、4和5)。

使用Javascript,我如何有条件地格式化表格中保存这些度量(特别是field2和field3)的单元格的背景颜色,使其与以下颜色相对应:

  • 带1的单元格为红色
  • 带有2、3和4的
  • 单元格为BLUE
  • 带5的细胞为GREEN

这是我到目前为止所做的(现在它都在一个HTML文件中,只是在我把它整理出来的时候),为了可读性,我把它分开了。我想我可能完全忽略了HTML中的背景属性。我知道这是可能的,但不确定如何动态地改变一个表格单元格的背景颜色取决于它的内容使用Javascript。

提前感谢。

脚本开始

<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(){
    $( "#status_report td.measure:contains('1')" ).css('background-color', '#fcc' );
});
</script>
<style type="text/css">
</style>
</head>
<body>
<table id="status_report">
<tr>
    <th>field1</th>
    <th>field2</th>
    <th>field3</th>
</tr>
<tr>
    <td class = "measure">Example</td>
    <td class = "measure">1</td>
    <td class = "measure">2</td>    
</tr>
</table>
</body>
</html>

更新:

注释指出了一个语法错误(额外的分号),该错误已被删除,以上代码工作正常。然而,有一个更好的答案已经被接受了。

即使使用PHP也可以这样做。为什么?因为JS是在客户端执行的,如果它被关闭,用户将看不到彩色的单元格。

<?php 
$colors = array(
  1 => "red",
  2 => "blue",
  3 => "blue",
  4 => "blue"
  5 => "green"
) ;
foreach( $data as $row ) : ?>
<tr>
  <?php foreach($row as $num): ?>
    <td style="background-color: <?php echo (isset($colors[(int)$num]) ? $colors[(int)$num] : "white") ; ?>"><?php echo $num ; ?></td>
  <?php endforeach ; ?>
</tr>   
<? endforeach; ?>

你也可以在td标签中使用类,而不是直接使用样式。

如果你还需要JQuery的解决方案,我可以编辑我的答案。

虽然您已经接受了答案,但JavaScript实现当然是可能的,这里使用纯JavaScript而不是jQuery:

function formatCells(table){
    var tbody = table.getElementsByTagName('tbody')[0],
        cells = tbody.getElementsByTagName('td'),
        colors = ['red', 'blue', 'green'];
    for (var c = 0, len = cells.length; c < len; c++){
        if (cells[c].cellIndex > 0){
            switch (parseInt((cells[c].textContent || cells[c].innerText), 10)){
                case 1:
                    cells[c].style.backgroundColor = colors[0];
                    break;
                case 2:
                case 3:
                case 4:
                    cells[c].style.backgroundColor = colors[1];
                    break;
                case 5:
                    cells[c].style.backgroundColor = colors[2];
                    break;
            }
        }
    }
}
formatCells(document.getElementsByTagName('table')[0]);

JS Fiddle demo.

给定您最近添加的HTML,您可以将上述内容应用到您自己的table中,如下所示:

formatCells(document.getElementById('status_report'));

JS Fiddle demo.

编辑以提供一个合理的(和可伸缩的)jQuery解决方案,而不是为每个可能的替代方案单独编写一行jQuery:

var colorMap = {
    1 : 'red',
    2 : 'blue',
    3 : 'blue',
    4 : 'blue',
    5 : 'green',
};
$('#status_report td').css('background-color', function(){
    return colorMap[$(this).text()] || '';
});

JS Fiddle demo.

并且,仅仅因为我喜欢纯JavaScript,我认为我应该提供一个演示如何通过扩展Object.prototype来实现相同的最终结果:

Object.prototype.propByTextValue = function(prop, obj){
    if (!obj){
        return this;
    }
    else {
        var that = this.length ? this : [this],
            txt = '';
        for (var i = 0, len = that.length; i < len; i++){
            that[i].style[prop] = obj[parseInt((that[i].textContent || that[i].innerText), 10)];
        }
    }
    return this;
};
var colorMap = {
    1 : 'red',
    2 : 'blue',
    3 : 'blue',
    4 : 'blue',
    5 : 'green',
};
document
.getElementById('status_report')
.getElementsByTagName('td')
.propByTextValue('background-color', colorMap);

JS提琴演示

为单元格添加数据属性:

<table id="status_report">
<tr>
    <th>fee_source_id</th>
    <th>field1</th>
    <th>field2</th>
    <th>field3</th>
</tr>
<?php foreach( $data as $row ) : ?>
<tr>
    <td data-bg="<?php echo $row['field1']; ?>"><?php echo $row['field1']; ?></td>
    <td data-bg="<?php echo $row['field2']; ?>"><?php echo $row['field2']; ?></td>
    <td data-bg="<?php echo $row['field3']; ?>"><?php echo $row['field3']; ?></td>  
</tr>
<? endforeach;
$dbh = null; ?>
</table>

和js:

$(document).ready(function(){
    $( "#status_report .measure[data-bg='1']").css('background', 'red');
    $( "#status_report .measure[data-bg='2']").css('background', 'blue');
    $( "#status_report .measure[data-bg='3']").css('background', 'blue');
    $( "#status_report .measure[data-bg='4']").css('background', 'blue');
    $( "#status_report .measure[data-bg='5']").css('background', 'green');
});

Demo: http://jsfiddle.net/pUw6u/