You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript表格status列根据值设置文本颜色失效的解决方法

问题解决:根据表格status列内容设置文本颜色

问题描述

用JavaScript读取本地source.json数据生成表格,需要给status列的文本设置颜色:pass为绿色、warn为黄色、error为红色,但颜色修改功能失效。

问题根源

  1. 重复ID冲突:生成表格时给所有status单元格用了相同的id="status",但HTML中id必须唯一,document.getElementById()只会返回第一个匹配元素,导致仅第一行可能被处理,其余行无效。
  2. 函数未执行:定义了f_color函数但从未调用,颜色设置逻辑根本没运行。
  3. DOM拼接低效:直接用innerHTML +=逐行拼接HTML,性能差且不利于后续元素操作。

修复方案

推荐两种可行方案,按需选择:

方案1:生成表格时直接设置样式

在拼接表格行的过程中,根据status值直接给单元格添加style属性,一步完成样式设置。

方案2:生成后遍历单元格(样式与结构分离)

给所有status单元格统一添加class,生成表格后通过class选择器批量获取元素,逐个判断内容设置颜色。


完整修复代码(方案1示例)

替换原index.html的JavaScript部分:

<!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>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>
    <table class="table table-striped">
        <tr class="bg-info">
            <th>unique_id</th>
            <th>max_loaded_at</th>
            <th>snapshotted_at</th>
            <th>max_loaded_at_time_ago_in_s</th>
            <th>status</th>
        </tr>
        <tbody id="myTable">
        </tbody>
    </table>
    <script>
        // 生成表格函数
        function buildTable(data) {
            const table = document.getElementById('myTable');
            let rows = '';
            for (const item of data) {
                // 根据status确定文本颜色
                let color = '';
                switch(item.status) {
                    case 'pass':
                        color = 'Green';
                        break;
                    case 'warn':
                        color = 'Yellow';
                        break;
                    case 'error':
                        color = 'Red';
                        break;
                }
                // 拼接行时直接嵌入样式
                rows += `<tr>
                            <td>${item.unique_id}</td>
                            <td>${item.max_loaded_at}</td>
                            <td>${item.snapshotted_at}</td>
                            <td>${item.max_loaded_at_time_ago_in_s}</td>
                            <td style="color: ${color}">${item.status}</td>
                        </tr>`;
            }
            table.innerHTML = rows; // 一次性插入所有行,提升性能
        }

        // 读取JSON数据
        fetch('source.json')
            .then(response => response.json())
            .then(data => {
                // 用map简化数据提取
                const source_data = data.results.map(item => ({
                    unique_id: item.unique_id,
                    max_loaded_at: item.max_loaded_at,
                    snapshotted_at: item.snapshotted_at,
                    max_loaded_at_time_ago_in_s: item.max_loaded_at_time_ago_in_s,
                    status: item.status
                }));
                buildTable(source_data);
            });
    </script>
</body>

</html>

完整修复代码(方案2示例)

通过CSS类控制颜色,实现样式与结构分离:

<!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>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <style>
        .status-pass { color: Green; }
        .status-warn { color: Yellow; }
        .status-error { color: Red; }
    </style>
</head>

<body>
    <table class="table table-striped">
        <tr class="bg-info">
            <th>unique_id</th>
            <th>max_loaded_at</th>
            <th>snapshotted_at</th>
            <th>max_loaded_at_time_ago_in_s</th>
            <th>status</th>
        </tr>
        <tbody id="myTable">
        </tbody>
    </table>
    <script>
        // 生成表格函数
        function buildTable(data) {
            const table = document.getElementById('myTable');
            let rows = '';
            for (const item of data) {
                // 根据status匹配对应CSS类
                let statusClass = '';
                switch(item.status) {
                    case 'pass':
                        statusClass = 'status-pass';
                        break;
                    case 'warn':
                        statusClass = 'status-warn';
                        break;
                    case 'error':
                        statusClass = 'status-error';
                        break;
                }
                rows += `<tr>
                            <td>${item.unique_id}</td>
                            <td>${item.max_loaded_at}</td>
                            <td>${item.snapshotted_at}</td>
                            <td>${item.max_loaded_at_time_ago_in_s}</td>
                            <td class="${statusClass}">${item.status}</td>
                        </tr>`;
            }
            table.innerHTML = rows;
        }

        // 读取JSON数据
        fetch('source.json')
            .then(response => response.json())
            .then(data => {
                const source_data = data.results.map(item => ({
                    unique_id: item.unique_id,
                    max_loaded_at: item.max_loaded_at,
                    snapshotted_at: item.snapshotted_at,
                    max_loaded_at_time_ago_in_s: item.max_loaded_at_time_ago_in_s,
                    status: item.status
                }));
                buildTable(source_data);
            });
    </script>
</body>

</html>

额外优化点

  • 用map替代for循环提取数据,代码更简洁。
  • 一次性拼接所有行再插入DOM,比逐行拼接性能更优。
  • 用switch-case替代多重if-else,逻辑更清晰易维护。

内容的提问来源于stack exchange,提问作者IOIOIOIOIOIOI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:05:21