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>
阅读 2.1k
1 个回答

这个是你想要的吗?

<!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>

希望能帮助到你。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题