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

如何在DataTable中实现动态Modal?模态框仅显示首行数据问题排查

问题根源与解决方案

你遇到的问题核心在于所有循环生成的模态框都使用了同一个id="myModal"——浏览器在查找元素时,只会匹配到第一个拥有该id的元素,所以不管你点击哪一行的按钮,弹出的永远是第一行对应的模态框,这也解释了为什么模态框内的{{forloop.counter}}始终显示1,因为你看到的一直是第一次循环生成的那个模态框。

下面是具体的修复步骤和修改后的代码:

1. 给每个模态框生成唯一ID

在循环里,用forloop.counter或者key作为后缀,给每个模态框赋予独一无二的id,比如myModal-{{forloop.counter}}。

2. 同步按钮的data-target属性

按钮的data-target要和对应模态框的id保持一致,这样点击按钮时才能精准触发对应的模态框。

3. 修复模态框的语法错误

你的代码里有一处明显的语法错误:<div class="modal-dialog"= {{ forloop.counter }}>,这里多余的=会导致HTML结构异常,需要移除。

修改后的完整代码

{% for key,value in config.items %}
  <td>
    <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-id="{{ key }}" data-target="#myModal-{{ forloop.counter }}">
      <i class="glyphicon glyphicon-pencil" aria-hidden="true"></i>
    </button>
    {{ key }}
  </td>

  <div class="modal fade" id="myModal-{{ forloop.counter }}" tabindex="-1" role="dialog" aria-labelledby="edit-{{ forloop.counter }}" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title custom_align" id="Heading">Edit Your Version for <strong>{{ key }}</strong></h4>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <input class="form-control" type="text" placeholder="{{ key }} ({{ forloop.counter }})">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-success btn-xs">
            <span class="glyphicon glyphicon-ok-sign"></span> Accept
          </button>
          <button type="button" class="btn btn-danger btn-xs">
            <span class="glyphicon glyphicon-remove-circle"></span> Reject
          </button>
        </div>
      </div>
    </div>
  </div>
{% endfor %}

额外优化建议

  • 给每个模态框的aria-labelledby也加上唯一标识(比如edit-{{ forloop.counter }}),提升页面的可访问性。
  • 输入框的placeholder属性建议用引号包裹,避免当key包含空格或特殊字符时出现HTML解析问题。

内容的提问来源于stack exchange,提问作者Nikhilsome

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:41:07