如何在单击链接时显示div,以及如何从输入中获取价值?

时间:2019-07-24 04:37:39

标签: html django templates

我有一个django模板,该模板使用for循环来打印我想显示输入字段的注释和单击编辑链接时的按钮,我该怎么做。 而且当按下编辑按钮时,我想从该特定输入字段中获取值。我该怎么办?

{% for comment in comments %}
<div class="comment mdl-color-text--grey-700">
   <header class="comment__header">
      <img src="images/co1.jpg" class="comment__avatar">
      <div class="comment__author">
         <strong>{{comment.User_name}}</strong>
         <span>{{comment.date}}</span>
      </div>
   </header>
   <div class="comment__text">
      {{comment.text}}
   </div>
   <!-- FAB button , class  "mdl-button--fab"-->
   <a href="javascript:delete_comment('{{comment.text}}','{{comment.blogslug}}')">
   <button class="mdl-button mdl-js-button mdl-button--fab">
   <i class="material-icons">delete</i>
   </button>
   </a>
    <!--when this link is clicked bellow edit_comment div should appear -->
   <a href="">
   <button class="mdl-button mdl-js-button mdl-button--fab">
   <i class="material-icons">edit</i>
   </button>
   </a>
    <!-- and also when i click the edit button how can i get value from the input -->
    <div id="edit_comment" style="visibility: hidden;">
        <input type="text" name="edit_comment">
        <button>edit</button>
    </div>
</div>
{% endfor %}

所以问题在于,还会有许多其他此类注释,因为它们是使用循环打印的。

1 个答案:

答案 0 :(得分:0)

首先,为什么将按钮包装在<a>标签中?不必要。

摆脱visibility: hidden。使用display: none或类似Bootstrap的d-none的类。

我建议使用d-none,因为它允许您添加类并删除它,而不必担心继承的显示属性,即display: flexdisplay: block

https://getbootstrap.com/docs/4.0/utilities/display/

使用事件侦听器编写自定义函数。

在模板循环中:

<button class="mdl-button mdl-js-button mdl-button--fab" onclick="handleClick(this)">
   <i class="material-icons">edit</i>
</button>

假设您已删除<a>标记

JavaScript:

let handleClick = function(param) {
    let editCommentDiv = param.parentNode.lastChild;
    editCommentDiv.style.display = "none"
};

这绝不是最好的方法。我强烈建议您使用BootStrap的d-none类。另外,您实际上应该做的是基于for循环为按钮和div分配一个ID,即id=editcommentdiv_{{ forloop.counter }}这样,您将不需要使用DOM导航到最后一个元素来获取编辑div,并且可以直接通过ID定位div。