如何修复Bootstrap 5模态框中删除帖子的ID关联问题?
问题根源
你的问题出在模态框ID重复上:在{% for post in page %}循环里,每个帖子的模态框都用了同一个id="exampleModal",而HTML中ID必须唯一。浏览器只会识别页面中第一个ID为exampleModal的元素,所以不管点击哪个帖子的删除按钮,都会触发第一个模态框,自然删除的是第一个帖子的ID。
两种解决方法
方法一:给每个模态框生成唯一ID
直接让每个帖子的模态框和触发按钮对应唯一ID,这样点击按钮会打开对应帖子的模态框,链接里的post.id自然是正确的。
修改代码如下:
{% for post in page %} <!-- 其他帖子内容不变 --> {% if user.username == profile_user.username %} <!-- 修改触发按钮的data-bs-target,加上post.id --> <button type="button" class="btn btn-sm text-muted" data-bs-toggle="modal" data-bs-target="#exampleModal-{{post.id}}"> ... </button> <!-- 修改模态框的id和label的id,加上post.id --> <div class="modal fade" id="exampleModal-{{post.id}}" tabindex="-1" aria-labelledby="exampleModalLabel-{{post.id}}" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel-{{post.id}}">Delete post?</h1> <button type="button" class="btn btn-sm text-muted" data-bs-dismiss="modal" aria-label="Close">...</button> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">NO</button> <a role="button" class="btn btn-primary" href="/profile/{{profile_user.username}}/{{post.id}}/delete">YES</a> </div> </div> </div> </div> {% endif %} {% endfor %}
方法二:用JavaScript动态更新删除链接
只保留一个模态框在循环外,点击删除按钮时,动态把当前帖子的ID传入模态框的链接中,这种方式更节省DOM资源,适合帖子数量多的场景。
步骤1:修改循环内的删除按钮
给按钮添加自定义属性,存储当前帖子的ID和用户名:
{% for post in page %} <!-- 其他帖子内容不变 --> {% if user.username == profile_user.username %} <button type="button" class="btn btn-sm text-muted delete-post-btn" data-bs-toggle="modal" data-bs-target="#exampleModal" data-post-id="{{post.id}}" data-username="{{profile_user.username}}"> ... </button> {% endif %} {% endfor %}
步骤2:把模态框移到循环外
确保页面只有一个模态框:
<!-- 放在{% endfor %}之后 --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Delete post?</h1> <button type="button" class="btn btn-sm text-muted" data-bs-dismiss="modal" aria-label="Close">...</button> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">NO</button> <!-- 给删除链接加个ID,方便JS修改 --> <a role="button" class="btn btn-primary" id="delete-post-link">YES</a> </div> </div> </div> </div>
步骤3:添加JavaScript代码
监听按钮点击事件,动态更新删除链接:
<script> document.querySelectorAll('.delete-post-btn').forEach(btn => { btn.addEventListener('click', function() { const postId = this.getAttribute('data-post-id'); const username = this.getAttribute('data-username'); const deleteLink = document.getElementById('delete-post-link'); deleteLink.href = `/profile/${username}/${postId}/delete`; }); }); </script>
内容的提问来源于stack exchange,提问作者Sifirus
相关产品推荐
相关产品推荐

