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

如何实现Flask生成的表格点击对应按钮单独显示/隐藏该行分数

问题根因

  • HTML 中 id 属性要求全局唯一,你在循环渲染每行时都给比分单元格设置了相同的 id="score",导致 document.getElementById("score") 永远只能匹配到页面中第一个符合条件的元素,所以只有第一行能触发显隐。
  • 另外 <td> 元素的默认展示属性是 table-cell 不是 block,直接设置 display:block 会导致单元格样式错位。

修复方案

第一步:修改HTML代码

把比分单元格的重复id替换为class,同时给点击事件传入当前触发的按钮对象this:

<table>
    {% for i in games %}
    <tbody>
        <tr>
            <td> {{i['homeTeam']}} </td>
            <!-- 把id替换为class,避免全局重复 -->
            <td style="display: none;" class="score"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
            <td> {{i['awayTeam']}} </td>
            <!-- 点击事件传入当前按钮对象 -->
            <td><button onclick="displayScore(this)">Reveal score</button></td>
        </tr>
    </tbody>
    {% endfor %}
</table>

第二步:修改JavaScript代码

通过传入的按钮对象向上查找对应行的比分单元格,单独控制当前行的显隐:

function displayScore(btn) {
    // 从当前按钮向上查找所属的行,再匹配行内的比分单元格
    var scoreTd = btn.closest('tr').querySelector('.score');
    if (scoreTd.style.display === "table-cell") {
        scoreTd.style.display = "none";
    } else {
        scoreTd.style.display = "table-cell";
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:15:03