在Microsoft Visual Studio中Bootstrap Modal无法显示的问题求助
从w3schools复制的Bootstrap模态框示例代码在在线HTML编译器中可正常运行,但粘贴到已安装jQuery NuGet包的Microsoft Visual Studio 2019空白Razor页面后,仅显示按钮,点击后模态框无任何反应。
示例代码:
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Activate Modal with JavaScript</h2> <!-- Trigger the modal with a button --> <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <script> $(document).ready(function () { $("#myBtn").click(function () { $("#myModal").modal('show'); }); }); </script> </body> </html>
解决jQuery重复加载/版本冲突
你已通过NuGet安装jQuery,但页面又引入了CDN版本,这会导致重复加载或版本冲突,直接破坏Bootstrap的事件绑定逻辑。
操作:删除页面中CDN的<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>,仅保留NuGet提供的本地jQuery引用。修正Bootstrap JS加载顺序
Bootstrap JS必须在jQuery之后加载。如果Razor页面的布局页将jQuery放在底部加载,而你手动在head中引入Bootstrap JS,会导致Bootstrap初始化时jQuery未就绪。
操作:将Bootstrap的JS脚本移到页面底部(</body>标签前),或确保在jQuery加载完成后再加载Bootstrap。禁用布局页避免资源冲突
空白Razor页面默认会使用_Layout.cshtml布局页,布局页可能已引入其他版本的jQuery或Bootstrap,与你手动添加的资源冲突。
操作:在Razor页面最顶部添加代码@{ Layout = null; },禁用布局页,确保页面仅加载你指定的资源。检查jQuery加载状态
打开浏览器开发者工具(F12)的控制台,查看是否有$ is not defined这类错误,确认jQuery是否成功加载。如果有错误,说明NuGet的jQuery引用路径配置有问题。
操作:通过NuGet重新安装jQuery,或手动检查页面中jQuery的引用路径是否正确。确认Bootstrap与jQuery版本兼容性
Bootstrap 3.4.1兼容jQuery 1.9.1至3.x版本,但如果NuGet安装的jQuery版本超出此范围,可能出现兼容性问题。
操作:在NuGet包管理器中检查jQuery版本,确保与Bootstrap 3.x匹配。
内容的提问来源于stack exchange,提问作者Macadamia1988

