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

如何将Bootstrap模态框接收的动态数据拼接至<embed>的src属性

解决Bootstrap模态框中动态设置PDF embed的src问题

现有代码情况

表格按钮代码

<td>
  <button type="button" class="btn btn-success btn-xs" 
          data-val="<?php echo $row['order_id']; ?>" 
          data-toggle="modal" 
          data-target="#my-modal" 
          data-order-id="<?php echo $row['order_id']; ?>">
    Update
  </button>
</td>

(注:原代码<td标签缺少闭合>,已修正)

现有模态框触发脚本

$('#my-modal').on('show.bs.modal', function (event) {
  var myVal = $(event.relatedTarget).data('val');
  $(this).find(".modal-body").text(myVal);
});

预期的PDF embed代码

<embed
  src="https://www.xx-xxxxx.com/image/waybill/ICE000??动态数据??.pdf"
  type="application/pdf"
  frameBorder="0"
  scrolling="auto"
  height="70%"
  width="150%"
></embed>

实现步骤

  1. 给embed标签添加唯一ID
    修改模态框内的embed标签,增加id属性以便jQuery定位:

    <embed
      id="waybill-pdf"
      src=""
      type="application/pdf"
      frameBorder="0"
      scrolling="auto"
      height="70%"
      width="150%"
    ></embed>
    
  2. 修改JS脚本,动态拼接并设置src
    在模态框的show.bs.modal事件中,获取订单ID、拼接PDF链接,再赋值给embed的src属性:

    $('#my-modal').on('show.bs.modal', function (event) {
      // 优先使用语义化的data-order-id获取订单ID
      var orderId = $(event.relatedTarget).data('order-id');
      // 拼接完整的PDF URL
      var pdfUrl = `https://www.xx-xxxxx.com/image/waybill/ICE000${orderId}.pdf`;
      // 给embed设置新的src
      $(this).find('#waybill-pdf').attr('src', pdfUrl);
      // 保留原有的显示订单ID到modal-body的逻辑(可选)
      $(this).find(".modal-body").text(orderId);
    });
    

额外说明

  • 推荐使用data-order-id而非data-val,属性名更具语义化,便于后期维护
  • 若需处理订单ID为空的异常情况,可增加判断逻辑:
    if (orderId) {
      $(this).find('#waybill-pdf').attr('src', pdfUrl).show();
      $(this).find(".modal-body").text(orderId);
    } else {
      $(this).find('#waybill-pdf').hide();
      $(this).find(".modal-body").text("无效的订单ID");
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:33:44