rails and bootstrap: Uncaught ReferenceError: jQuery is not defined

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I created a simple webapp integrating bootstrap 3 in a rails 3.2.17 application, following this procedure found on stackoverflow, so without using a gem but manually copying the bootstrap files in the relevant app directories.

Even if i have, in my gem file:

gem 'jquery-rails' 

i can still see, inspecting my web page with chrome, the error:

Uncaught ReferenceError: jQuery is not defined  

My page is a "normal" html page in public directory. Maybe it doesn't "inherit" all the assets stuff? The code is like this:

  <!DOCTYPE html> <html> <head>     <title>Bootsrap Test 01</title>     <link rel="stylesheet" href="/css/bootstrap.css">     <script src="/js/bootstrap.min.js" type="text/javascript"></script> </head>  ... 

I've not yet tried but i guess that javascript based feature won't work.

回答1:

Assuming that after adding gem 'jquery-rails', you have ran bundle install command.

Make sure you have following in app/assets/javascripts/application.js

//= require jquery //= require jquery_ujs //= require bootstrap.min   // Add it after jquery and jquery_ujs 

EDIT

You will need to explicitly include jQuery before including /bootstrap.min.js. For example :

<!DOCTYPE html> <html> <head>     <title>Bootsrap Test 01</title>     <link rel="stylesheet" href="/css/bootstrap.css">     <script src="/assets/jquery.js" type="text/javascript"></script>     <script src="/assets/jquery_ujs.js" type="text/javascript"></script>     <script src="/js/bootstrap.min.js" type="text/javascript"></script> </head> 


回答2:

Even if you have set jquery correctly you can still see that issue when you inline javascript code is evoked before jQuery is initialized.

You can wrap your javascript code in

document.addEventListener("DOMContentLoaded", function(event) {    //do work with $ }); 

Or refactor your code to not use inline javascript :)



回答3:

on 'application.js' of rails 5.0.1 the default is

//= require bootstrap //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . 

change it to

//= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . //= require bootstrap 

*load first jquery before bootstrap



回答4:

Another place to check is the <head> of the application.html.erb file.

Be sure that you're loading in jQuery before the Bootstrap javascript.



回答5:

I came across the same error message in the console.

Just make sure jQuery is above Bootstrap in your 'assets/javascripts/application.js' file

Solution:

//= require jquery //= require jquery_ujs //= require jquery-ui //= require bootstrap 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!