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

使用JQuery向Bootstrap模态框传递数据问题求助

解决jQuery向模态框传递数据的问题

我来帮你排查代码里的几个关键问题,调整后就能实现点击「Read More」展示详情的功能了:

问题1:data-id格式冗余

你HTML里的data-id="(string)<?=$ourExpertiseTitle?>"多了不必要的(string)前缀,PHP直接输出变量值即可,data属性会自动识别字符串类型,修正后:

data-id="<?= $ourExpertiseTitle ?>"

问题2:a标签默认跳转干扰模态框

空的href=""会触发页面跳转,导致模态框无法正常显示。推荐在jQuery事件中阻止默认行为(避免页面锚点跳转),也可以把href设为#。

问题3:错误使用val()方法赋值

.modal-body一般是div元素,val()方法仅适用于表单元素(如input、textarea),应该用text()或html()来设置内容:

$(".modal-body").text(myourid);

问题4:模态框选择器不匹配

你的HTML中data-target=".bs-example-modal-lg"是类选择器,但jQuery里用了$('#mymodal')(id选择器),两者需要统一。建议给模态框添加id并对应。


修正后的完整代码

HTML部分(含模态框结构)

<a id="readMore" class="george" href="#" data-toggle="modal" data-target="#mymodal" data-id="<?= $ourExpertiseTitle ?>">Read More</a>

<!-- 模态框结构,注意id与data-target一致 -->
<div class="modal fade bs-example-modal-lg" id="mymodal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myLargeModalLabel">详情</h4>
      </div>
      <div class="modal-body">
        <!-- 这里会展示传递的详情内容 -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

jQuery部分

<script>
$(document).on('click', ".george", function(event) {
  // 阻止a标签默认跳转行为
  event.preventDefault();
  
  // 获取data-id的值
  var myourid = $(this).data('id');
  
  // 将内容赋值给模态框主体
  $(".modal-body").text(myourid);
  
  // 弹出模态框
  $('#mymodal').modal('show');
});
</script>

这样调整后,点击按钮就能正常把$ourExpertiseTitle的值传递到模态框里展示啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:40:28