1

我正在尝试实现一个切换来为 Django 模板上的循环语句中的每个元素显示一个隐藏的 DIV。问题是我只能让它在循环的第一个元素上工作,或者同时在所有元素上工作(一个按钮触发每个隐藏的 DIV 显示)。如何使用 vanilla JS 或在最坏的情况下使用 Jquery 来实现这一点?

这是我模板中的 html

{% for comment in comments%}
            <div class="comment">
                <p><strong>{{comment.author}} {% if comment.author == article.author%}[Seller]{% endif %}</strong> said:</p>
                <p>{{comment.commentary}} {% if user.is_authenticated and article.status == "Active" and article.author == user %}<button id="test" class="test" onclick="myFunction()">Reply>></button></p>
                <div class="reply_box_container" id="reply_box_container" style="display:none">
                    <p><strong>Reply:</strong></p>
                    <form>
                        <div id="reply_textarea_container"><textarea  name="comment_textarea" rows="2" cols="50" placeholder="Write your reply here"></textarea></div>
                        <div id="reply_btn_container"><button class="btn btn-secondary" type="submit" name="comment_btn">submit</button></div>
                    </form>
                </div>
                {% endif %} 
                    {% if reply%}
                        <span class="reply">
                            <p><strong>{{article.author}}</strong> replied:</p>
                            <p>{{reply}}</p>
                        </span>
                    {% endif %}
                    <hr></hr>
            </div>  
        {% endfor %}

这里是我尝试使用的 Jquery:

    <script>
$(document).ready(function(){
  $(".test").click(function(){
    $(".reply_box_container").toggle();
  });
});
</script>
4

1 回答 1

1

您走在正确的道路上,之所以只使用第一个元素或所有元素,是因为您在每个元素中都有相同的 id,请尝试提供一个唯一的 id,例如id="reply_box_container-{{ forloop.counter }}". 请记住, 也id="test"应该是唯一的,您可以在click函数中传递计数器。有关 Django 中循环计数器的更多参考,请单击此处

于 2021-03-09T03:44:11.627 回答