Grails与Bootstrap v4组合抛出Uncaught TypeError的原因是什么?
解决Bootstrap v4引入Grails 2.3.11后出现的"Uncaught TypeError: Cannot read property 'fn' of undefined"错误
这个错误我碰到过好多次!核心原因很简单:Bootstrap v4的JavaScript组件完全依赖jQuery,但你目前的布局里只加载了Bootstrap的JS,没有提前引入jQuery,导致Bootstrap在初始化时找不到jQuery的fn对象(这是jQuery用来扩展插件的核心属性),直接抛出了类型错误。
具体解决方案
你需要调整资源引入的顺序,先加载jQuery,再加载Bootstrap的JS文件,步骤如下:
- 选择一个兼容Bootstrap v4的jQuery版本(Bootstrap v4要求jQuery 1.9.1及以上,考虑到Grails 2.3.11的版本较老,推荐用jQuery 3.5.1这类稳定且兼容的版本)
- 在你的Grails布局GSP中,把jQuery的引入代码放在Bootstrap JS的前面
修改后的布局代码示例
<!DOCTYPE html> <!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]--> <!--[if IE 7 ]> <html lang="en" class="no-js ie7"> <![endif]--> <!--[if IE 8 ]> <html lang="en" class="no-js ie8"> <![endif]--> <!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]--> <!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]--> <head> <!-- 其他头部资源(比如Bootstrap CSS) --> </head> <body> <!-- 页面内容 --> <!-- 先引入jQuery --> <script src="/path/to/jquery-3.5.1.min.js"></script> <!-- 再引入Bootstrap JS --> <script src="/path/to/bootstrap.min.js"></script> </body> </html>
额外注意事项
如果你在用Grails的Resources插件管理静态资源,记得在ApplicationResources.groovy里配置依赖顺序,确保jQuery在Bootstrap JS之前加载,比如:
modules = { core { dependsOn 'jquery' resource url: '/js/bootstrap.min.js' } }
这样调整后,Bootstrap就能正常找到jQuery的fn对象,不会再抛出这个错误啦!
内容的提问来源于stack exchange,提问作者Bmoe
相关产品推荐
相关产品推荐

