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

如何解决Ajax取数后用jQuery对表格td条件格式化的函数未定义报错

问题修复方案

存在的问题

  • ajaxCall1 定义在setInterval的匿名函数参数内,属于函数作用域变量,全局无法访问,调用时报未定义错误。
  • 循环生成表格行时重复使用相同id(team1-score/team2-score),id为全局唯一标识,getElementById仅会返回第一个匹配元素,无法遍历所有行的得分单元格。
  • 样式更新逻辑和数据渲染逻辑脱离,没有在每次表格重渲染后自动触发。

修改方案

  • 将ajaxCall1提取为全局函数,保留定时调用逻辑。
  • 把得分单元格的id属性改为class属性,避免标识重复。
  • 将条件格式化逻辑直接放在ajax请求的done回调末尾,表格DOM渲染完成后立刻执行样式更新。

完整修改后代码

<!doctype html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainstyle.css') }}">
<script>
// 将ajaxCall1提取为全局函数
function ajaxCall1() {
  $.ajax({
    url: "/nfl_data",
    type: "GET",
    dataType: "json",
  })
  .done( function (response) {
    var tableHTML = '';
    tableHTML += '<tr><th colspan="1"> 比赛日期 </th><th> 队伍1</th><th colspan="2">胜率 </th><th>队伍2 </th><th colspan="2">得分 </th></tr>';

    $.each(response, function (i, item) {
      // 把id替换为class避免重复
      tableHTML += '<tr><td>' + item.GameDate + '</td><td>' + item.Team1+ '</td><td>' + item.Team1Prob + '</td><td>' + item.Team2Prob + '</td><td>' + item.Team2 + '</td><td class="team1-score">' + item.Team1Score + '</td><td class="team2-score">' + item.Team2Score+'</td></tr>';
    });
    $("#game-data").html(tableHTML);
    
    // 表格渲染完成后直接执行条件格式化
    $('#game-data tr').not(':first').each(function() {
      const t1Score = parseInt($(this).find('.team1-score').text());
      const t2Score = parseInt($(this).find('.team2-score').text());
      if (t1Score > t2Score) {
        $(this).find('.team1-score').css('background-color', '#e8630a');
      } else if (t2Score > t1Score) {
        $(this).find('.team2-score').css('background-color', '#e8630a');
      }
    })
  });
}
// 定时调用函数
setInterval(ajaxCall1, 1000);
</script>
<div id="pageHead">
    
</div>
<div id="game-wrapper">
  <table  id="game-data">
  </table>
</div>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:24:03