Laravel中Ajax调用模态框失效,报错$(...).modal is not a function
解决Bootstrap 5中
$(...).modal is not a function报错问题 问题原因
你遇到的报错核心原因是Bootstrap 5完全移除了基于jQuery的API支持,Bootstrap 4及更早版本里的$(element).modal('show')这类jQuery写法在Bootstrap 5中不再生效。同时你的模态框HTML代码还是Bootstrap 4的旧属性写法,和Bootstrap 5的规范不兼容。
修复步骤
1. 更新模态框HTML代码,适配Bootstrap 5
替换旧的属性,使用Bootstrap 5统一的data-bs-*前缀属性,同时更新关闭按钮的样式规范:
<div class="content"> <!-- Modal --> <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <!-- 替换旧close按钮为Bootstrap5标准btn-close --> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <!-- 替换data-dismiss为data-bs-dismiss --> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <a class="edit_click btn btn-warning">Edit</a> </div>
2. 修改JS代码,使用Bootstrap 5原生API
放弃jQuery的modal()方法,改用Bootstrap 5官方提供的Modal类来控制模态框:
// 原生JS写法(无需jQuery,推荐) document.addEventListener('DOMContentLoaded', function() { document.querySelector('.edit_click').addEventListener('click', function() { // 创建模态框实例并调用show方法 const editModal = new bootstrap.Modal(document.getElementById('editModal')); editModal.show(); }); });
如果你的项目必须保留jQuery,也可以兼容写法:
$(function() { $('.edit_click').click(function() { // 获取DOM元素后创建Modal实例 const editModal = new bootstrap.Modal($('#editModal')[0]); editModal.show(); }); });
3. 可选优化:清理不必要的依赖
Bootstrap 5不需要jQuery即可运行,如果你的项目没有其他地方用到jQuery,可以直接移除<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>这一行,减少页面加载负担。
内容的提问来源于stack exchange,提问作者GamaRay
相关产品推荐
相关产品推荐

