【问题标题】:How do I hide/reveal a single item that is generated by Flask?如何隐藏/显示 Flask 生成的单个项目?
【发布时间】:2021-09-30 16:29:59
【问题描述】:

我想在点击时显示表格中一行的分数。

现在它只隐藏和显示第一个分数。有什么办法可以做到,所以当我按下按钮时,它不会显示所有分数。谢谢! 这是我尝试过的:

HTML:

            <table>
                {% for i in games %}
                <tbody>
                    <tr>
                        <td> {{i['homeTeam']}} </td>
                        <td style="display: none;" id="score"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
                        <td> {{i['awayTeam']}} </td>
                        <td><button onclick="displayScore()">Reveal score</button></td>
                    </tr>
                </tbody>
                {% endfor %}
            </table>

Javascript:

function displayScore() {
    var x = document.getElementById("score");
    if (x.style.display === "block") {
      x.style.display = "none";
    } else {
      x.style.display = "block";
    }
}

【问题讨论】:

    标签: javascript python css flask


    【解决方案1】:
    1. ID 必须是唯一的。在您的代码中,您在多个元素(多个 tds)上使用相同的 id。您可以使用循环索引使您的 id 独一无二。尝试这样的事情
    <td style="display: none;" id="score_{{loop.index}}"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
    

    这会给你类似score_1, score_2, etc

    1. 为每个按钮添加数据属性,以便您可以识别单击了哪个按钮。还要删除每个按钮上的onclick 代码(我们将用事件侦听器替换它。类似
    <td><button data-index="{{loop.index}}">Reveal score</button></td>
    
    1. 现在向表格主体添加一个点击事件侦听器。由于每个按钮都在一个表格行内,该行也在表格主体内,单击该按钮将导致事件“冒泡”到表格主体,这将触发您附加到表格主体的侦听器。

      事件监听器附加到表格主体而不是直接附加到按钮,因为您的按钮是动态生成的,即按钮是在运行时添加的(在您的 javascript 代码已经存在之后),这意味着系统不知道这些按钮.

        document.querySelector("tbody").onclick = function(e){
            // Find out which elem which was clicked
            const clicked_elem = e.target;
    
            // If this clicked elem is a button, then execute our code
            if (clicked_elem.tagName == "BUTTON"){
                // First identify which button was clicked
                const index = clicked_elem.dataset.index
    
                // Now get the td corresponding to that button
                var x = document.getElementById("score_" + index);
    
                if (x.style.display === "block") {
                  x.style.display = "none";
                } else {
                  x.style.display = "block";
                }
            }
          
        }
    

    【讨论】:

    • 感谢您的回答,但是当我实现您的代码时,只有第一项(data-index=1)有效并且能够出现/消失。更新:我将document.querySelector("tbody") 更改为document.querySelector("table"),它似乎有效。非常感谢!
    • 刚刚注意到您的代码存在问题(这就是为什么我的原始代码不适合您的原因)。你的神器循环应该在 之后而不是之前。使用您当前的代码,您将在单个 中有多个 ,这在语义上没有意义。如果你修复它,那么我的原始代码将起作用
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多