正如你从图片中看到的,我在一个页面中有几种形式。每个表单都有自己的块和评论列表。一个页面中的多个表单更新混凝土块?
我成功地通过AJAX/JQuery更新评论块后成功添加新的评论的形式。可以说,如果用户通过三维形式添加评论AJAX需要更新三维形式的三维评论块。下面你可以看到我的JS代码。
问题是,当我对所有表单(任务评论表单)使用相同的id,并且所有评论块(task-comments)的相同id都很好地只用第一种形式。当我提交第二个或第三个表格时,它会更新第一个注释块。我认为JS从上到下检查文档并找到第一个匹配。
当我对所有表单和注释块使用相同的类时,它的工作方式也是错误的。例如,当我提交所有3个评论块更新的第二个表单。
那么如何将特定的表单与特定的注释块相关联?
JS:
$(document).ready(function() {
$('.submit').on("click", function() {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this).closest('form');
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#task-comments").html(data.html_task_comment);
}
else {
$("#task-comment-form").html(data.html_task_comment_form);
}
}
});
$("#task-comment-form")[0].reset();
return false;
});
});
task_list.html:
<div class="list-group custom-list-group">
<div class="list-group-item bg-faded">
{% include 'project/task_comment_form.html' %}
</div>
<div id="task-comments-{{ forloop.counter }}">
{% include 'project/task_comment_list.html' %}
</div>
</div>
task_comment_form.html:
<form method="post" id="task-comment-form-{{ forloop.counter }}" action="{% url 'project:task_comment_add' project_code=project.code group_task_code=group_task.code task_code=task.code %}">
<button type="submit"></button>
</form>
task_comment_list.html:
{% for comment in task.comments.all %}
<div class="list-group-item flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h6 class="mb-1">{{ comment.author }}</h6>
<small>{{ comment.created }}</small>
</div>
<p class="custom-p">{{ comment.text }}</p>
</div>
{% empty %}
<div class="list-group-item flex-column align-items-start">
<div class="d-flex w-100 justify-content-center">
<h6 class="mb-1 custom-h"><i class="fa fa-info-circle" aria-hidden="true"></i>	{% trans 'NO COMMENTS' %}</h6>
</div>
</div>
{% endfor %}
您好!你能再次检查我的帖子,请。我添加我的HTML。我在ID中使用{{forloop.counter}}。所以现在每个表单和块注释都有唯一的ID。但是我对你的JS代码有一点点补充。看来我需要改变commentBoxId中的内容。你怎么看? –
表单的数量也不固定。在这里我只举了三种形式的例子。实际上,它们可以大于或小于3.在模板中,我可以使用'task-comments - {{forloop.counter}}}和'task-comment-form - {{forloop.counter}}'但是不知道在JS中使用它。对不起我的英语不好。 –
你好。您可以在HTML中再次使用计数器来设置“data-comment”属性。数据评论属性应设置为您在评论框中使用的ID。然后,JavaScript可以获取此数据注释值,使用它来查找指定的评论框,并仅更新该框。 –