You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flask删除HTML表格数据,点击删除按钮传错ID如何解决

问题根源

你的代码出错是因为Bootstrap模态框的ID重复:

  • HTML规范要求页面内所有元素的ID必须唯一,你在for循环遍历用户列表时,给每一行的模态框都设置了相同的ID confirmModal,触发模态框的按钮的data-bs-target也都指向同一个ID #confirmModal
  • 浏览器解析DOM时,遇到重复ID只会匹配第一个出现的元素,所以不管你点击哪一行的删除按钮,弹出的都是第一行对应的模态框,模态框内的删除链接自然携带的是第一行的用户ID,就会出现删错行的问题。

解决方案

给每个模态框的ID加上对应用户的唯一ID,保证所有ID不重复,同时修改触发按钮的指向、模态框的关联属性即可,修改后的核心代码片段如下:

<!-- 只需要修改for循环内的按钮和模态框部分 -->
<!-- Button trigger modal -->
<button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#confirmModal{{uid}}">
  <i style="color:red" class="fa fa-times fa-1x"></i>
</button>

<!-- Modal -->
<div class="modal fade" id="confirmModal{{uid}}" tabindex="-1" aria-labelledby="confirmModalLabel{{uid}}" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="confirmModalLabel{{uid}}">Confirm Delete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure you want to delete this user?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <a href="/processDeleteUser/{{uid}}" class="btn btn-danger" role="button">Delete</a>
      </div>
    </div>
  </div>
</div>

如果不想给每一行都生成独立模态框,也可以只保留一个全局模态框,点击删除按钮时动态把对应用户ID赋值给模态框的删除链接,能减少页面冗余DOM节点,上述改法是适配现有代码成本最低的方案,修改后即可正常运行。

内容的提问来源于stack exchange,提问作者Mike C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 21:15:07