table下的单元格使用innerHTML,怎么为其添加样式?
我为一个表格插入一些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>
回复
1个回答

test
2024-06-30
这个是你想要的吗?
<!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);
resultCell.style.color = item.fenshu >= 80 ? "auto" : "red";
}
function calculateResult(score) {
if (score >= 80) {
return "通过";
} else {
return "不通过";
}
}
</script>
希望能帮助到你。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容