如何根据点击的按钮动态切换Bootstrap模态框(modal)的内容
实现方案
核心通过Bootstrap模态框的原生事件获取触发按钮标识,动态控制内容显隐,具体修改如下:
1. 调整HTML结构
首先给每个触发按钮添加自定义属性标记要展示的内容类,同时修正原有代码中第三个内容区块的类名错误:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- 给每个按钮添加data-content-class属性指定对应展示的内容类 --> <button type="button" class="btn" data-toggle="modal" data-target="#exampleModalCenter" data-content-class="one">one</button> <button type="button" class="btn" data-toggle="modal" data-target="#exampleModalCenter" data-content-class="two">two</button> <button type="button" class="btn" data-toggle="modal" data-target="#exampleModalCenter" data-content-class="three">three</button> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" 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">×</span> </button> </div> <div class="modal-body"> <div class="content-block one">Button one content</div> <div class="content-block two">Button two content</div> <!-- 修正原代码类名错误,从one改为three --> <div class="content-block three">Button three content</div> </div> </div> </div> </div>
这里统一给所有内容区块加了content-block类,方便后续统一控制隐藏。
2. 添加控制逻辑JS
监听模态框的show.bs.modal事件,在模态框显示前动态切换内容显隐:
// 监听模态框显示事件 $('#exampleModalCenter').on('show.bs.modal', function (e) { // 获取触发模态框的按钮元素 const triggerBtn = $(e.relatedTarget); // 获取要展示的内容类名 const targetClass = triggerBtn.data('content-class'); // 先隐藏所有内容区块 $('.content-block').hide(); // 显示对应类名的内容区块 $(`.content-block.${targetClass}`).show(); })
如果需要手动触发模态框切换,仍然可以使用你提供的代码:$('#exampleModalCenter').modal('toggle')
内容的提问来源于stack exchange,提问作者Jordan Kellet
相关产品推荐
相关产品推荐

