如何使用jquery创建一个动态下拉式表单?

问题描述 投票:0回答:1

我正在做一个Django项目,我想实现一个按钮点击后的下拉式表单。我有一个下拉式表单,当一个按钮被点击时,每个表单都有自己的按钮,问题是当我点击一个特定的表单按钮时,所有其他表单也会下拉。我只想让这个特定的表单下拉,而其他表单不下拉。我认为这与将表单的id传递给每个被点击的按钮有关。这是我试过的。

enter image description here

模板。

{% for comment in all_comments %}
<ul>
<li class="float-right">
<!--Dropdown-->
<div class="dropdown dropdown-commentdeleteedit">
<a data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-h grey-text"></i>
</a>
<!-- Menu -->
<div class="dropdown-menu font-small z-depth-1">
<a class="dropdown-item material-tooltip-email editform-dropdown" data-toggle="tooltip" data-placement="top" title="Edit">
<img src="{{ '/static/' }}images/edit24px.png" width="18" height="18"></a>
</div>
</div>
<!--Dropdown-->
</li>
{% endif %}
<h6 class="comment editcomment-text ml-5">
{{ comment.comment_post }}
</h6>

<!-- DROPDOWN EDIT COMMENT FORM -->
<form  method="POST" enctype="multipart/form-data" class="ajaxcomment-editform editcommentform editcomment-form mb-4" id="" action="{% url 'site:comment_update' post.id comment.id %}">
{% csrf_token %}
<textarea name="comment_post" cols="20" rows="5" required="" id="id_comment_post{{ comment.id }}">{{ comment.comment_post }}</textarea>
<button type="submit" class="btn btn-sm waves-effect z-depth-1">Save</button>
</form>
</ul>
{% endfor %}

Jquery:

<script type="text/javascript">
//HIDE AND SHOW COMMENT EDIT FORM ON DROPDOWN
$(document).on('click', '.editform-dropdown', function(){
 $('.editcommentform').show();
 $('.editcomment-text').hide();
})
</script>
html jquery django dropdown
1个回答
1
投票

它打开所有的下拉菜单,因为 $('.editcommentform') 选择DOM中所有带有类的元素。editcommentform. 范围太广。

你需要在处理函数中添加一个事件参数,然后引用一下 event.target 中的函数来访问被点击的实际对象。然后您可以访问准确的 .editcommentform.editcomment-text 你想显示和隐藏的元素。

类似这样的操作应该是可行的。

<script type="text/javascript">
//HIDE AND SHOW COMMENT EDIT FORM ON DROPDOWN
$(document).on('click', '.editform-dropdown', function(event){
  $(event.target).closest('li').find('.editcommentform').show();
  $(event.target).closest('li').find('.editcomment-text').hide();
})
</script>

调用 $(event.target).closest('li') 选择最接近的母体 li 元素到被点击的对象,然后调用 find('classname') 选择该家长的子女,并将其与该类的 editcommentform.

这里有一个基于你的代码的提琴,展示了它是如何工作的。https:/jsfiddle.netBenjaminRaykfbvo6zL。

© www.soinside.com 2019 - 2024. All rights reserved.