根据单元格值格式化HTML / jquery表格单元格的颜色

时间:2017-02-21 21:39:07

标签: jquery html css

我有以下HTML,它使用jquery从csv文件中提取数据并将其显示在表中。我试图在结果表上进行一些条件格式化。我希望任何值低于2.5的单元格设置为绿色背景。 2.5到3之间的值应为黄色。 3到100之间的任何值都应为红色。我已尝试过网站上提供的众多不同解决方案,但迄今为止都没有。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatiable" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inspection</title>
<link rel="stylesheet" href="mystyles.css" />
<meta http-equiv="refresh" content="120">


</head>
<body>

<script src="jquery.min.js"></script>
<script>
function opsi(data){
    var allRows = data.split(/\r?\n|\r/);
    var table = "<table id='scrapT'>";
    for(var singleRow=0;singleRow<allRows.length;singleRow++){
        if(singleRow === 0){
            table += "<thead>";
            table += "<tr>";
        } else{
            table += "<tr>";
        }
        var rowCells = allRows[singleRow].split(',');
        for(var rowSingleCell=0;rowSingleCell<rowCells.length;rowSingleCell++){
            if(singleRow === 0){
                table += "<th>";
                table += rowCells[rowSingleCell];
                table += "</th>";
            } else{
                table += "<td>";
                table += rowCells[rowSingleCell];
                table += "</td>";
            }
        }
        if(singleRow === 0){
            table += "</tr>";
            table += "</thead>";
            table += "<tbody>";
        } else{
            table += "</tr>";
        }
    }
    table += "</tbody";
    table += "</table>";
    $("body").append(table);
}

$.ajax({
    url: "file.csv",
    dataType: "text"
}).done(opsi);

</script>

1 个答案:

答案 0 :(得分:1)

这是一个很好的链接,有一个可以引用的例子。

Changing background cell of table depending on value