【问题标题】:color p tags with different colors based on for loop in Django template基于Django模板中的for循环为不同颜色的p标签着色
【发布时间】:2021-09-04 06:09:49
【问题描述】:

我正在创建一个应用程序,将多个测验的答案显示在一个页面上。

为此,我有一个for 循环,它循环遍历每个循环,并在该循环中使用if 标签将正确答案涂成绿色。但是,所有测验都得到相同的答案颜色,因为 css 样式不会停留在每个 for 循环之间。

我怎样才能阻止这种情况?

{% for quiz in Quizes %}
    <div class="question-Card">
        <p id="a"> A:{{choice1}}
        <p id="b"> A:{{choice2}}
        <p id="c"> A:{{choice3}}
        <p id="d"> A:{{choice4}}

        {% if quiz.answer == 'a' %}
            <style>
                #a {
                color: green;
                }
            </style>
        {% endif %}

        **this then continues for the other choices 
but the code isn't the issue, so I will save you the read** 

    </div>
{% endfor %}

问题是,如果要“阅读”的最后一个测验是 c 色,那么它们都是 c 色的,并且它不会单独完成每个测验,请帮助

【问题讨论】:

  • 问题是下一个问题可以有'a'作为答案,并且由于id都相同,这意味着样式也将应用于下一个条目的样式。

标签: javascript html css django


【解决方案1】:

问题是下一个问题可以有'a' 作为答案,并且由于id 都是相同的,这意味着样式也将应用于下一个条目的样式。通常你不应该给两个 DOM 项赋予相同的 id。

我们可以通过简单地将其添加为style="…" 属性来解决这个问题:

{% for quiz in Quizes %}
  <div class="question-Card">
    <p {% if quiz.answer == 'a' %}style="color:green"{% endif %}> A:{{choice1}}
    <p {% if quiz.answer == 'b' %}style="color:green"{% endif %}> A:{{choice2}}
    <p {% if quiz.answer == 'c' %}style="color:green"{% endif %}> A:{{choice3}}
    <p {% if quiz.answer == 'd' %}style="color:green"{% endif %}> A:{{choice4}}
  </div>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2015-04-14
    • 2012-03-28
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多