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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:40:35