Javascript html表格单元格的条件格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5066882/
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-23 15:29:49  来源:igfitidea点击:

conditional formatting of html table cells

javascripthtmljquery-uijsphtml-table

提问by Salman A. Kagzi

Are there any out of the box solutions to have conditional formatting of HTML tables?

是否有任何开箱即用的解决方案来对 HTML 表格进行条件格式设置?

With conditional formatting I am more interested in having different colors as cell background depending on the value (numeric) of that or some other column (in the same table).

对于条件格式,我更感兴趣的是根据该列或其他列(在同一个表中)的值(数字)将不同的颜色作为单元格背景。

Something similar to what we have in excel Conditional Formating -> Color Scales -> Red Yellow Green. I want to implement that in a table that is being dynamically generated via JSP.

类似于我们在 excel 条件格式 -> 色阶 -> 红黄绿中的内容。我想在通过 JSP 动态生成的表中实现它。

Are there any JavaScript/jquery or JSP solutions for this?

是否有任何 JavaScript/jquery 或 JSP 解决方案?

采纳答案by Salman A. Kagzi

I have done similar to similar to what ZDYN and David propose but in a more mathematically proven way.

我做了类似于 ZDYN 和 David 提出的类似的事情,但以一种更数学证明的方式。

After my dynamic values are calculated I go around calculating percentiles for the columns that I want to color code using

在计算我的动态值后,我开始计算要使用颜色编码的列的百分位数

(L/N)*100
where: L=> Number of Items less the value for which percentile is being calculated
N => Total number of items

(L/N)*100
其中:L=> 项目数减去正在计算的百分位数
N => 项目总数

Now, depending on the percentile I get from the above calculations, appropriate colors are assigned for use when displaying the table.
With this approach I get the flexibility of using different color palettes at different granularity levels as the need be.
For example I can use Red for percentile ranging from 0-5 in one case and 0-10 in another. All these parts can be flexibly coded for as all of the above steps are done @ backend. (in Java)

现在,根据我从上述计算中得到的百分位数,在显示表格时会分配适当的颜色以供使用。
通过这种方法,我可以根据需要灵活地使用不同粒度级别的不同调色板。
例如,我可以将红色用于百分比范围,在一种情况下为 0-5,在另一种情况下为 0-10。所有这些部分都可以灵活编码,因为上述所有步骤都在后端完成。(在 Java 中)

回答by Stofke

http://jsfiddle.net/stofke/Ya68Q/

http://jsfiddle.net/stofke/Ya68Q/

      $(function() {
            $('tr > td:odd').each(function(index) {
                var scale = [['vPoor', 10], ['poor', 50], ['avg', 250], ['good', 1250], ['vGood', 6250]];
                var score = $(this).text();
                for (var i = 0; i < scale.length; i++) {
                    if (score <= scale[i][1]) {
                        $(this).addClass(scale[i][0]);
                    }
                }
            });
       });

回答by David says reinstate Monica

My first take on this, given the following table structure:

考虑到以下表结构,我对此的第一个看法:

<table>
    <col id="name" />
    <col id="score" />
    <thead>
        <tr>
            <th>Name</th>
            <th>Score</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Allan, Paul</td>
            <td>28</td>
        </tr>
        <tr>
            <td>Bartlett, James</td>
            <td>33</td>
        </tr>
        <tr>
            <td>Callow, Simon</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Dennis, Mark</td>
            <td>19</td>
        </tr>
        <tr>
            <td>Ennals, Simon</td>
            <td>10</td>
        </tr>
        <tr>
            <td>Finnegan, Seamus</td>
            <td>21</td>
        </tr>
    </tbody>
</table>

css:

css:

table {
    width: 20em;
}

#score {
    width: 50%;
}

#name {
    width: 50%;
}

th {
    border-bottom: 2px solid #000;
    padding: 0.5em 0 0.1em 0;
    font-size: 1.2em;
}

td {
    border-bottom: 2px solid #ccc;
    padding: 0.5em 0 0.1em 0;
}

th:nth-child(even),
td:nth-child(even) {
    text-align: center;
}

.vGood {
    background-color: #0f0;
}

.good {
    background-color: #0c0;
}

.avg {
    background-color: #060;
}

.poor {
    background-color: #c00;
}

.vPoor {
    background-color: #f00;
}

and jQuery:

和 jQuery:

$('tbody tr td:not(":first")').each(

function() {
    var vGood = 30,
        good = 25,
        avg = 20,
        poor = 15,
        vPoor = 10,
        score = $(this).text();

    if (score >= vGood) {
        $(this).addClass('vGood');
    }
    else if (score < vGood && score >= good) {
        $(this).addClass('good');
    }
    else if (score <good && score >= avg) {
        $(this).addClass('avg');
    }
    else if (score < avg&& score >= poor) {
        $(this).addClass('poor');
    }
    else if (score < poor) {
        $(this).addClass('vPoor');
    }
    });

JS Fiddle demo.

JS小提琴演示

This is, of course, a brute-force approach. It'll work, but it's not the most optimised/efficient approach.

当然,这是一种蛮力方法。它会起作用,但它不是最优化/最有效的方法。

回答by Ortund

You could set up some css classes:

你可以设置一些css类:

.row { background-color: #00ff00; }
.alt { backgorund-color: #ff00ff; }

<table>
    <tr class="row">
        <td>&lt;cell contents go here&gt;</td>
    </tr>
    <tr class="alt">
        <td>&lt;cell contents go here&gt;</td>
    </tr>
</table>

The jquery option is also simple, but this is how I would do it honestly.

jquery 选项也很简单,但老实说,这就是我要做的。

HTH

HTH

回答by zdyn

Maintain two variables for highest and lowest values in the table.

为表中的最高值和最低值保留两个变量。

Add a function that gets called any time the table changes. Iterate through each cell and recalculate the highest and lowest values as necessary and then with an if statement (or something similar) reassign the correct color. For example, for each cell:

添加一个在表更改时调用的函数。遍历每个单元格并根据需要重新计算最高和最低值,然后使用 if 语句(或类似的东西)重新分配正确的颜色。例如,对于每个单元格:

if(cellValue < minValue)
    minValue = cellValue;
else if(cellValue > maxValue)
    maxValue = cellValue;

var bracket = (cellValue - minValue) / (maxValue - minValue);

if(bracket < .2)
    // make the cell green
else if(bracket < .4)
    // make the cell green-yellow
else if(bracket < .6)
    // make the cell yellow

...and so on. This is very brute force though. You can probably find a way to optimize the process of reassigning colors to existing cells.

...等等。虽然这是非常暴力的。您可能会找到一种方法来优化将颜色重新分配给现有单元格的过程。

回答by user2733277

You could use css and dynamically generate class names on the backend... so on the backend, you would add class="level1" (or "level2" or "level3" etc) based on the calculated value of the cell. Then you could control the display of those classes through simple css.

您可以使用 css 并在后端动态生成类名...因此在后端,您将根据单元格的计算值添加 class="level1"(或“level2”或“level3”等)。然后你可以通过简单的 css 控制这些类的显示。