【问题标题】:how to show the div when clicked on the link and how to get value from input?单击链接时如何显示 div 以及如何从输入中获取值?
【发布时间】:2019-07-24 04:37:39
【问题描述】:

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

{% 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 %}

所以问题是这种类型的许多其他 cmets 因为它们是使用循环打印的。

【问题讨论】:

  • 使用 {{ forloop.counter }} 在 for 循环中获取一个计数器,并将其添加到 divs 的 id 属性中。单击按钮时,将其作为参数传递给您的 JavaScript 函数。

标签: html django templates


【解决方案1】:

首先,为什么要将按钮包装在&lt;a&gt; 标记中?不必要。

摆脱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>

假设您已删除 &lt;a&gt; 标签

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。

【讨论】:

  • 在editCommentDiv之后的同一个JavaScript函数中,editCommentDiv.firstChild.value
  • 再一次,你应该使用 ID
猜你喜欢
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2016-05-19
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多