如何在Laravel 9中使用Bootstrap Modal?弹窗不显示需JS吗?
在Laravel 9里用Bootstrap Modal的正确姿势
一、要不要用JavaScript?
Bootstrap Modal本身依赖Bootstrap的JS文件,所以必须确保页面加载了对应的JS资源,不然肯定用不了。不过不用自己写复杂JS:
- 简单场景:直接用Bootstrap自带的
data-*属性就能触发Modal,不用手写JS。 - 复杂需求:比如要在打开Modal前做验证、动态加载内容,就可以用Bootstrap的JS API手动控制,比如Bootstrap 5里可以这么写:
const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal')); deleteModal.show();
二、你的Modal点了没反应?先改这俩问题
看你贴的代码,直接原因有两个:
- 属性拼写错了:按钮里的
data-toggle="madal"是笔误,应该是modal(如果是Bootstrap 4);要是用的Bootstrap 5,得改成data-bs-toggle="modal"和data-bs-target="#deleteModal"。 - 多了个闭合标签:Modal代码最后多了一个
</div>,DOM结构乱了,删掉就行。
修复后的代码示例
用Bootstrap 4的情况:
<button class="btn btn-sm" data-toggle="modal" data-target="#deleteModal"> <i class="bi bi-slash-circle"></i> </button> <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "delete" below if you are sure you want to delete this skill.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="{{route('deleteSkill', [$Skill->id])}}">delete</a> </div> </div> </div> </div>
用Bootstrap 5的情况:
注意属性都要加bs-前缀,关闭按钮也换了样式:
<button class="btn btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal"> <i class="bi bi-slash-circle"></i> </button> <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body">Select "delete" below if you are sure you want to delete this skill.</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="{{route('deleteSkill', [$Skill->id])}}">delete</a> </div> </div> </div> </div>
三、Laravel 9里要确保Bootstrap资源装对了
- 用Laravel UI安装:
先装依赖:composer require laravel/ui,然后生成Bootstrap模板:php artisan ui bootstrap,最后编译资源:npm install && npm run dev。
然后在布局文件(比如resources/views/layouts/app.blade.php)里引入编译好的文件:<link href="{{ asset('css/app.css') }}" rel="stylesheet"> <script src="{{ asset('js/app.js') }}"></script> - 用CDN的话:
页面头部加Bootstrap CSS,底部加Bootstrap JS(Bootstrap 5不用jQuery,Bootstrap 4得先引jQuery)。
四、额外提醒
- Modal的
id和按钮的data-target/data-bs-target必须完全一致,大小写都不能错。 - 别在Modal里套多余的div,不然DOM结构错了也会显示异常。
- 要是按钮是循环生成的(比如列表里的删除按钮),得保证每个Modal的
id唯一,或者用JS动态绑定事件。
内容的提问来源于stack exchange,提问作者yyy
相关产品推荐
相关产品推荐

