简体   繁体   English

使用 Django 中的按钮关闭所有 forms

[英]Close all forms with a button in Django

I building a threaded comment system (Reddit-like) in Django 3.0我在 Django 3.0 中构建了一个线程评论系统(类似 Reddit)
A comment can have as many replies as possible.一条评论可以有尽可能多的回复。 For each comment made, a Reply form is shown below it.对于每条评论,其下方都会显示一个回复表单。 Now, if I don't hide the forms, the page looks very bad, cluttered with textareas.现在,如果我不隐藏 forms,页面看起来很糟糕,文本区域杂乱无章。

I need the following: A 'Reply' button, clicking which the reply form can be displayed/hidden.我需要以下内容:“回复”按钮,单击可以显示/隐藏回复表单。

Here's what I have tried:这是我尝试过的:

  1. Added a class .replyForm to the forms.向 forms 添加了 class .replyForm
    Added a class .hideBtn to the hide Buttons.在隐藏按钮中添加了 class .hideBtn
    Used JQuery:二手 JQuery:
  $(".hideBtn").click(function(){
        $(".replyForm").toggle();
    });

Now, this works fine, but clicking a reply button opens up all the forms at the same time.现在,这工作正常,但单击回复按钮会同时打开所有 forms。
This is expected as the class belonging to each form is the same.这是预期的,因为属于每种形式的 class 是相同的。

  1. Using Django's template tags I managed to make the id of each form and button unique.使用 Django 的模板标签,我设法使每个表单和按钮的 id 都是唯一的。
    Example: id = "replyForm{{comment.id}}" which renders as replyForm123 if comment.id = 123示例: id = "replyForm{{comment.id}}"如果comment.id = 123 ,则呈现为replyForm123
    But I am not able to use this in any productive way.但我无法以任何有效的方式使用它。
    I can't access the id outside the for loop (which displays the comments).我无法访问 for 循环(显示评论)之外的 id。
    I tried adding the JQuery script inside the loop, and created 2 variable, one for the id for the button, and other for the form's id.我尝试在循环中添加 JQuery 脚本,并创建了 2 个变量,一个用于按钮的 id,另一个用于表单的 id。
    But as the loop executes, the variables change accordingly, and finally they store the id's of the last comment only, rendering all the other toggle buttons useless.但是随着循环的执行,变量会相应地改变,最后它们只存储最后一条评论的 id,使所有其他切换按钮无用。

I feel that I am complicating things way too much, I am very new to JS and JQuery, and I'am only using them because I couldn't find a pythonic/django-based way for doing this.我觉得我把事情复杂化了太多,我对 JS 和 JQuery 很陌生,我之所以使用它们,是因为我找不到基于 pythonic/django 的方法来执行此操作。

Is there a simpler, more elegant way for doing this?有没有更简单、更优雅的方法来做到这一点? Any help is appreciated任何帮助表示赞赏

Edit 1:编辑1:
I have found a very simple solution using Bootstrap 4's collapse class , but still want to know the JQuery way of doing this.我找到了一个非常简单的解决方案,使用Bootstrap 4 的崩溃 class ,但仍然想知道 JQuery 这样做的方式。

Try this:尝试这个:

$(".replyForm").click(function(){
    $(this).toggle();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM