jQuery not working on Rails 3.2.8

后端 未结 4 1693
一向
一向 2021-01-19 22:07

I\'m having an issue with jQuery on Rails 3.2.8. I\'ve installed the jquery-rails gem and my application.js has the following:

//= require jquery
//= require         


        
相关标签:
4条回答
  • 2021-01-19 22:16

    You probably want to check the console in the browser you are testing.

    In jQuery's case, $ is just an alias for jQuery, does the following work

    jQuery(document).ready(function(){
       jQuery("a").click(function(event){
         alert("Thanks for visiting!");
       });
    });
    

    Perhaps you have called jQuery.noConflict() somewhere, removing the alias?

    http://api.jquery.com/jQuery.noConflict/

    0 讨论(0)
  • 2021-01-19 22:25

    Although its too late for an answer but still i'll provide as i was having the same problem and wasted like 2 hours on it. Remove the comments in your js file as they are ruby comments and not js comments. If you remove them and write your js code, it'll work fine.

    0 讨论(0)
  • 2021-01-19 22:33

    Fixed it!

    in application.html.erb, I changed the ordering of these two lines from:

    <%= stylesheet_link_tag    "application", :media => "all" %>
    <%= javascript_include_tag "application" %>
    

    to:

    <%= javascript_include_tag "application" %>
    <%= stylesheet_link_tag    "application", :media => "all" %>
    

    Now it works! I'm not quite sure why though, can anybody explain?

    0 讨论(0)
  • 2021-01-19 22:39

    Make sure you're including the javascript include tag before the yield in your application.html.erb. If you're using Bootstrap, I think the default application.rb loads JS after the yield, which makes it necessary to wait until jQuery is loaded before running it in your views.

    If that's the case and you don't want to relocate the include tag higher on the page, you can do this:

    runScript();
    function runScript() {
        if( window.$ ) { // Make sure jquery is loaded
             // your jquery code here
        } else {
            window.setTimeout(runScript, 100); // If not, wait 100 milliseconds and try again.
        }
    }
    
    0 讨论(0)
提交回复
热议问题