问题
I'm trying to use the Select2 plugin to add a search bar to my select box.
I get the following error when looking at the page console :
Uncaught ReferenceError: $ is not defined
Searching different questions here led me to believe this error happens because the jQuery javascript is not included or put before the script is called. But I still could not find a way to make it work. How can I fix this error and make the select2 plugin work?
Here is the application.js file :
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require select2
//= require tinymce
//= require turbolinks
//= require_tree
I've tried rearranging the order of select2 in the application.js file in many different ways with no success (I tried to make sure jQuery was loaded right before Select2).
Here is the index.html.haml file :
%select{:id => "test"}
- @lamps.each do |lamp|
%option{:value => "1"}= lamp.brand + ' ' + lamp.category + ' ' + lamp.lamptype + ' (' + lamp.cct.to_s + 'K)'
:javascript
$(document).ready(function() { $("#test").select2(); });
Here is the application.html.haml file :
!!! 5
%html
%head
%title= t('.lspdd_light_spectral_power_dis')
%meta{:name => "viewport", :content=>"width=device-width, user-scalable=no"}
= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true
= javascript_include_tag "application", "data-turbolinks-track" => true, :defer => "defer"
= javascript_include_tag "d3.min.js", :defer => "defer"
= csrf_meta_tags
Additionnal information :
- Rails version : 4.0.3
- ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
Thank you!
Edit #1:
Adding the a screenshot of the information displayed by the network dev-tool.
http://imgur.com/QJGCM2b
If I understand correctly the application-ea826f14bc5ea6f6976b187ce8d3008e.js file includes everything mentionned in the application.js file?
回答1:
dont use //= require_tree
if you already include all you scripts manualy. this can be the cause of errors. remove this string and try to reload page
p.s i also think what you are using incorrect sintax
//= require_tree
correct version contain dot
//= require_tree .
p.p.s. not about your main question, but you are using old version of ruby. check the newer
one more important thing what i didn't mentiond before. you are using defer="defer"
attribute for deffering main script loading. inline javascript what you type on page loaded BEFORE main scripts
来源:https://stackoverflow.com/questions/35205226/is-not-defined-uncaught-referenceerror-while-using-select2-plugin-with-rails