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

如何基于按钮ID或名称打开不同模态框 单模态框代码适配方案

实现方案

核心逻辑

在表单提交触发时提前捕获对应要弹出的模态框选择器,异步AJAX请求成功后直接用预存的选择器调用模态框展示方法即可,解决固定ID无法适配多模态框的问题。

代码修改

HTML部分(支持多表单多模态框适配)

给每个提交按钮新增data-target-modal属性,值为对应要弹出的模态框ID选择器,灵活度更高,不需要强制ID命名规则:

<!-- 测试表单1 -->
<form action="https://test.com/testme.html" method="post" class="ajax">
<button class="item" id="test1" name="testing" value="1" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test1" data-target-modal="#test1_modal">
测试按钮1
</button>
</form>

<!-- 测试表单2 -->
<form action="https://test.com/testme.html" method="post" class="ajax">
<button class="item" id="test2" name="testing" value="2" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test2" data-target-modal="#test2_modal">
测试按钮2
</button>
</form>

<!-- 对应模态框 -->
<div class="modal fade" id="test1_modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body"></div>
    </div>
  </div>
</div>
<div class="modal fade" id="test2_modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body"></div>
    </div>
  </div>
</div>

JavaScript部分

$(document).ready(function() {
  $('form.ajax').on('submit', function(event) {
    event.preventDefault();
    const that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};
    // 提交时提前获取当前按钮对应的目标模态框选择器
    const targetModal = that.find('button[type="submit"]').data('target-modal');

    that.find('[name]').each(function(index, value) {
      const cur = $(this),
      name = cur.attr('name'),
      val = cur.val();
      data[name] = val;
    });

    $.ajax({
      url: url,
      type: type,
      data: data,
      success: function(response){
        // 给对应模态框写入返回内容并弹出
        $(targetModal).find('.modal-body').html(response);
        $(targetModal).modal('show');
      }
    });
  });
});

可选简化方案

如果不想额外加data属性,也可以通过按钮ID和模态框ID的命名规则匹配实现,比如按钮ID为test1,对应模态框ID固定为modal_test1,只需要把获取targetModal的逻辑替换为:

const btnId = that.find('button[type="submit"]').attr('id');
const targetModal = `#modal_${btnId}`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:45:05