我为一个表格插入一些json数值,其中某个单元格,希望为其添加样式。如下代码,我想为每行的单元格4做一个判断,如果是不通过,就自动增加font:red,让这个值显眼一点。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
<th>分数</th>
<th>结果</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
<script>
var stu = [
{ name: "张三", sex: "男", fenshu: "100" },
{ name: "李四", sex: "男", fenshu: "60" },
{ name: "王五", sex: "男", fenshu: "90" },
];
const table = document.getElementById("myTable");
const tbody = table.getElementsByTagName("tbody")[0];
for (let i = 0; i < stu.length; i++) {
const item = stu[i];
const row = tbody.insertRow(i);
const nameCell = row.insertCell(0);
nameCell.innerHTML = item.name;
const sexCell = row.insertCell(1);
sexCell.innerHTML = item.sex;
const scoreCell = row.insertCell(2);
scoreCell.innerHTML = item.fenshu;
const resultCell = row.insertCell(3);
resultCell.innerHTML = calculateResult(item.fenshu);
}
function calculateResult(score) {
if (score >= 80) {
return "通过";
} else {
return "不通过";
}
}
</script>
这个是你想要的吗?
希望能帮助到你。