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

使用JavaScript根据动态值修改<td>背景色,仅部分状态样式生效问题排查

问题排查与修复方案

存在的问题

  • 样式覆盖不满足业务规则
    你当前仅定义了online、offline、down三个状态对应的CSS类,业务要求的「其余状态显示橙色」没有对应样式规则;同时你直接把接口返回的状态值作为td的类名,非以上三种的状态没有匹配的样式,自然不会生效。
  • JS逻辑冗余错误
    外层已经写了$(document).ready,请求成功回调里又重复嵌套了$(document).ready,还同时用了for循环+forEach两次遍历接口返回的数组,属于完全多余的重复逻辑,容易引发渲染异常。
  • 状态判断逻辑空置
    你写的多分支if-else没有任何实质处理逻辑,没有对非在线/离线的状态做统一类名处理,导致异常状态的类名零散无法匹配样式。

修复代码

JS代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
// 封装请求方法,方便后续定时刷新调用
function fetchStatus() {
  $.ajax({
    url: 'http://localhost/api/job/',
    dataType: 'JSON',
    success: function (data) {
      var content = ''
      data.forEach(item => {
        let statusClass = ''
        let statusStr = item.system_status.toLowerCase()
        // 按业务规则匹配类名
        if (statusStr.indexOf('online') === 0) {
          statusClass = 'online'
        } else if (statusStr.indexOf('offline') === 0) {
          statusClass = 'offline'
        } else {
          // 所有非在线/离线的状态统一用other类
          statusClass = 'other'
        }
        content += `<tr><td class="${statusClass}">${item.system_status}</td></tr>`
      })
      $('#table_body').html(content);
    }
  });
}

$(document).ready(function () {
  // 页面加载时首次请求
  fetchStatus()
  // 每5分钟刷新一次状态,可根据需求调整间隔时长
  setInterval(fetchStatus, 5 * 60 * 1000)
});
</script>

CSS+HTML代码

<style>
  td.online {
    background-color: #a4bc31;
  }
  td.offline {
    background-color: #bc3131;
  }
  /* 其余状态橙色 */
  td.other {
    background-color: orange;
  }
</style>
<body>
<table>
  <tbody id='table_body'></tbody>
</table>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:24:05