如何修复Uncaught TypeError: Cannot read properties of undefined (reading 'backdrop')错误?
问题解决:Bootstrap模态框初始化报错(Cannot read properties of undefined 'backdrop')
错误原因分析
控制台抛出的Cannot read properties of undefined (reading 'backdrop')错误,核心是模态框重复初始化冲突:你在img标签上设置了data-bs-toggle="modal"和data-bs-target="#exampleModal",这会让Bootstrap自动绑定点击事件并初始化模态框;同时又通过jQuery手动绑定click事件调用modal('show'),两者的初始化逻辑冲突,导致模态框实例创建失败。另外,模态框结构不完整也可能触发这类初始化异常。
分步解决方案
1. 移除自动触发属性
删除img标签上的data-bs-toggle和data-bs-target属性,避免Bootstrap自动触发模态框初始化:
<a id="myLink" href="/p/{{ $post->id }}"> <img src="/storage/{{ $post->image }}" alt="" class="me-1" style="border-collapse: separate; height: 320px; width: 320px; object-fit: cover"> </a>
2. 补全模态框完整结构
Bootstrap模态框必须包含.modal-dialog、.modal-content等核心结构,否则无法正常初始化。补全你的模态框代码:
<div class="modal" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">帖子详情</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <!-- 帖子内容将加载到这里 --> </div> </div> </div> </div>
3. 优化jQuery点击事件逻辑
将加载内容和显示模态框的操作分开,确保内容加载完成后再显示模态框,避免实例初始化异常:
$('a#myLink').on('click', function(e) { e.preventDefault(); const modal = $('#exampleModal'); const postUrl = $(this).attr('href'); // 先加载帖子内容,加载完成后再显示模态框 modal.find('.modal-body').load(postUrl, function() { modal.modal('show'); }); });
4. 检查版本兼容性
确保你的jQuery版本与Bootstrap版本匹配:
- Bootstrap 5 需要 jQuery 3.6.0 及以上版本
- Bootstrap 4 需要 jQuery 1.9.1 及以上版本
同时确保引入顺序正确:先引入jQuery,再引入Bootstrap的JS文件。
内容的提问来源于stack exchange,提问作者nguyenld
相关产品推荐
相关产品推荐

