如何使用javascript根据其值更改单元格的背景颜色?

时间:2021-10-10 20:17:54

I have a table with 3 columns:

我有一个包含3列的表格:

  • field1 is a Category
  • field1是一个类别

  • field2 and field3 hold Measures (integers 1,2,3,4 and 5 to be exact).
  • field2和field3保存Measures(确切地说是整数1,2,3,4和5)。

Using Javascript, how can I conditionally format the background color of the cells in the table that hold these measures (notably field2 and field3) to correspond with the following colors:

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

  • cells with 1 are RED
  • 具有1的细胞是RED

  • cells with 2,3, and 4 are BLUE
  • 2,3和4的细胞是蓝色的

  • cells with 5 are GREEN
  • 5的细胞是绿色的

Here's what I have so far (it's all in one HTML file for now, just while I get it sorted out) and I've broken it up for readability. I think I might be missing the background attribute in the HTML altogether. I know its possible, but not sure how to dynamically change the background color of a table cell depending on its contents using Javascript.

这是我到目前为止所有的内容(现在它只在一个HTML文件中,就在我整理出来的时候),为了便于阅读,我已将其分解。我想我可能完全错过了HTML中的background属性。我知道它可能,但不知道如何使用Javascript根据其内容动态更改表格单元格的背景颜色。

Thanks in advance.

提前致谢。

Start of the script

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

Update:

A comment pointed out a syntax error (extra semi-colon) which was removed and the above code works fine. However, there was an even better answer posted and has been accepted.

注释指出了一个语法错误(额外的分号)被删除,上面的代码工作正常。但是,有一个更好的答案发布并已被接受。

3 个解决方案

#1


4  

You could do it even with PHP. Why? Because JS is executed on client-side and if it is turned off, users will not see the colored cells.

你甚至可以用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; ?>

You could use classes in td tags as well instead of straight style.

您也可以使用td标签中的类而不是直线型。

If you still need a solution with JQuery, I can edit my answer.

如果您仍然需要使用JQuery的解决方案,我可以编辑我的答案。

#2


3  

While you've accepted an answer, a JavaScript implementation is certainly possible, here using plain JavaScript rather than 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.

JS小提琴演示。

Given your recently-added HTML, you could apply the above to your own table as follows:

鉴于您最近添加的HTML,您可以将以上内容应用于您自己的表,如下所示:

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

JS Fiddle demo.

JS小提琴演示。

Edited to offer a sane (and scalable) jQuery solution, rather than having a separate line of jQuery for every possible alternative:

编辑提供一个理智(和可扩展)的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.

JS小提琴演示。

And, just because I like plain JavaScript, I thought I'd offer a demonstration of how to achieve the same end-result by extending the Object.prototype:

而且,仅仅因为我喜欢简单的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 Fiddle demo.

JS小提琴演示。

#3


2  

Add data attributes to your cells:

向您的单元格添加数据属性:

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

And the js :

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

演示:http://jsfiddle.net/pUw6u/

#1


4  

You could do it even with PHP. Why? Because JS is executed on client-side and if it is turned off, users will not see the colored cells.

你甚至可以用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; ?>

You could use classes in td tags as well instead of straight style.

您也可以使用td标签中的类而不是直线型。

If you still need a solution with JQuery, I can edit my answer.

如果您仍然需要使用JQuery的解决方案,我可以编辑我的答案。

#2


3  

While you've accepted an answer, a JavaScript implementation is certainly possible, here using plain JavaScript rather than 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.

JS小提琴演示。

Given your recently-added HTML, you could apply the above to your own table as follows:

鉴于您最近添加的HTML,您可以将以上内容应用于您自己的表,如下所示:

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

JS Fiddle demo.

JS小提琴演示。

Edited to offer a sane (and scalable) jQuery solution, rather than having a separate line of jQuery for every possible alternative:

编辑提供一个理智(和可扩展)的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.

JS小提琴演示。

And, just because I like plain JavaScript, I thought I'd offer a demonstration of how to achieve the same end-result by extending the Object.prototype:

而且,仅仅因为我喜欢简单的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 Fiddle demo.

JS小提琴演示。

#3


2  

Add data attributes to your cells:

向您的单元格添加数据属性:

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

And the js :

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

演示:http://jsfiddle.net/pUw6u/