根据 Javascript 中的条件以特定颜色(红色或绿色)在表中显示 JSON 值



我有一条 JSON 消息,需要以表格格式显示,如下所示。我正在尝试根据值以不同的颜色显示标记、感知、结果列。低于 40% 的任何内容都是失败的,因此 Rick 的分数、百分比和结果值将以红色显示,而对于其他学生,这三列应为绿色。

必填表:

NAME     SEX    MARKS   PERCENTAGE   RESULT
Rick      M    32/100      32          F
Rose      F    43/45       95.96       P
Alex      M    54/75       72          P
Adam      M    88/96       91.67       P

JSON 消息:

[{"NAME":"Rick","SEX":"M","MARKS":"32/100","PERCENTAGE":"32%","RESULT":"F"},{"NAME":"Rose","SEX":"F","MARKS":"43/45","PERCENTAGE":"95.56%","RESULT":"P"},{"NAME":"Alex","SEX":"M","MARKS":"54/75","PERCENTAGE":"72%","RESULT":"P"},{"NAME":"Adam","SEX":"M","MARKS":"88/96","PERCENTAGE":"91.67%","RESULT":"P"}]

我已经编写了以下代码,它以表格格式显示数据。

<!DOCTYPE html>
<html>
<head>
<title>Spring Session Report</title>
<style>
table, th, td 
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
text-align: center;
}
th {
font-weight:bold;
background-color:#b1babf;
color: black; 
font-size: 15px;
text-align: center;
margin: auto;
padding: 8px;
height: 5px;
width: 20%;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Generate Semester Report" />
<div id="showData"></div>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = [{"NAME":"Rick","SEX":"M","MARKS":"32/100","PERCENTAGE":"32%","RESULT":"F"},{"NAME":"Rose","SEX":"F","MARKS":"43/45","PERCENTAGE":"95.56%","RESULT":"P"},{"NAME":"Alex","SEX":"M","MARKS":"54/75","PERCENTAGE":"72%","RESULT":"P"},{"NAME":"Adam","SEX":"M","MARKS":"88/96","PERCENTAGE":"91.67%","RESULT":"P"}]
var col = [];
for (var i = 0; i < myReport.length; i++) {
for (var key in myReport[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);                 
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");     
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < myReport.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myReport[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>

我知道标记,百分比,结果列的颜色需要使用CSS来完成,但我不确定如何实现它。还是有更好的方法?在这方面有人可以提供帮助吗?

检查每次迭代的百分比,并根据百分比是否为每个tr提供一个passfail类。然后,您可以使用nth-child设置最后几个TD的样式。

您还可以使用数组方法显着清理Javascript:

function CreateTableFromJSON() {
var myBooks=[{"NAME":"Rick","SEX":"M","MARKS":"32/100","PERCENTAGE":"32%","RESULT":"F"},{"NAME":"Rose","SEX":"F","MARKS":"43/45","PERCENTAGE":"95.56%","RESULT":"P"},{"NAME":"Alex","SEX":"M","MARKS":"54/75","PERCENTAGE":"72%","RESULT":"P"},{"NAME":"Adam","SEX":"M","MARKS":"88/96","PERCENTAGE":"91.67%","RESULT":"P"}]
const divContainer = document.getElementById("showData");
divContainer.textContent = '';
const table = divContainer.appendChild(document.createElement("table"));
const trHead = table.appendChild(document.createElement('tr'));
Object.keys(myBooks[0]).forEach(key => {
trHead.appendChild(document.createElement('th'))
.textContent = key;
});
myBooks.forEach((personData) => {
const tr = table.appendChild(document.createElement('tr'));
const percentStr = personData.PERCENTAGE;
const percent = Number(percentStr.slice(0, percentStr.length - 1));
if (percent < 40) tr.className = 'fail';
else tr.className = 'pass';
Object.values(personData).forEach(tableValue => {
tr.appendChild(document.createElement('td'))
.textContent = tableValue;
});
});
}
table,
th,
td {
margin: 10px 0;
border: solid 1px #333;
padding: 2px 4px;
font: 15px Verdana;
text-align: center;
}
th {
font-weight: bold;
background-color: #b1babf;
color: black;
font-size: 15px;
text-align: center;
margin: auto;
padding: 8px;
height: 5px;
width: 20%;
}
tr.pass > td:nth-child(n + 3) {
color: green;
}
tr.fail > td:nth-child(n + 3) {
color: red;
}
<input type="button" onclick="CreateTableFromJSON()" value="Generate Semester Report" />
<div id="showData"></div>

您可以有两个类,每种可能的颜色对应一个类:

.red {
background: red;
}
.green {
background: green;
}

然后,根据百分比是否低于40%,您可以应用其中一个:

const percentage = parseFloat(student.PERCENTAGE); // No need to remove the % at the end.
tableCell.classList.add(percentage < 40 ? 'red' : 'green')

完整示例:

// Data:
const students = [{
"NAME":"Rick",
"SEX":"M",
"MARKS":"32/100",
"PERCENTAGE":"32%",
"RESULT":"F"
}, {
"NAME":"Rose",
"SEX":"F",
"MARKS":"43/45",
"PERCENTAGE":"95.56%",
"RESULT":"P"
}, {
"NAME":"Alex",
"SEX":"M",
"MARKS":"54/75",
"PERCENTAGE":"72%",
"RESULT":"P"
}, {
"NAME":"Adam",
"SEX":"M",
"MARKS":"88/96",
"PERCENTAGE":"91.67%",
"RESULT":"P"
}];
// Get a list with all column names:
const columnNames = Object.keys(students[0]);
// And create another one with the ones we want to add a background based
// on the value of the percentage:
const columnNamesWithBackground = ["MARKS", "PERCENTAGE", "RESULT"];
// Create the table:
const table = document.createElement("table");
// Create the header of the table:
const header = table.insertRow();
for (const columnName of columnNames) {
const th = document.createElement("th"); 

th.innerText = columnName;

header.appendChild(th);
}
// Create the content of the table:
for (const student of students) {
// Add a new row at the end:
tr = table.insertRow(-1);
// Get the percentage and parse it as a number:
const percentage = parseFloat(student.PERCENTAGE);
// Add all the columns and values to this row:
for (const columnName of columnNames) {
const td = tr.insertCell(-1);

if (columnName === 'SEX') {
td.classList.add('borderRight');
} else if (columnNamesWithBackground.includes(columnName)) {
td.classList.add(percentage < 40 ? 'red' : 'green');
}

td.innerText = student[columnName];
}  
}
// Add the table to the page:
document.body.appendChild(table);
body {
font-family: monospace;
font-size: 16px;
}
table {
border: 2px solid #000;
border-collapse: collapse;
table-layout: fixed;
text-align: center;
width: 100%;
}
th,
td {
border-bottom: 2px solid #000;
padding: 4px;
}
th {
padding: 8px;
background: #000;
color: #FFF; 
font-weight: bold;
width: 20%;
}
.green {
background: #0A2;
color: #FFF;
}
.red {
background: #F00;
color: #FFF;
}
.borderRight {
border-right: 2px solid #000;
}

最新更新