简体   繁体   中英

js code does not work in Rails

I put some js code in the application.js fileand it does not work...

application.js:

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

//...

obj.dd.on('click', function(event){
    $(this).toggleClass('active');
    return false;
});

//...

$(function() {

    var dd = new DropDown( $('#dd') );

    $(document).click(function() {
        // all dropdowns
        $('.wrapper-dropdown-5').removeClass('active');
    });

});

also iI activated a line in the initializers/assets.rb file:

 Rails.application.config.assets.precompile += %w( search.js )

but anyway my code is unavailable for using in a view. I think there should be nothing extra, as it is in the application.js.

Or may be there should be something else?

1) Have you mentioned this in your application layout??

<%= javascript_include_tag 'application', 'data-turbolinks-track' =>  true %>

2) After this, use alert message in your application.js

alert('Hello');

Working javascript that is in applications.js will work. So I'm guessing your problem isn't the application.js part of it, it's your function isn't working.

Add a console.log 'clicked' to your click function to see if fires on click. I think your javascript problem could be tied to your click function not in a document.ready() function.

Rails.application.config.assets.precompile += %w( search.js )

By looking above line of code. I guess you have search.js file. Whenever you want to use external js file(manually added) then you have to inform application.js file to include such file.

So your application.js file should be( If you wanted to add search.js which is not under app/assets/javascript/ and placed under vendor/assets/javascript/ )

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require search  #js file will be added like this without it's extension 
//= require_tree .

Note: //= require_tree will include all js files which are under app/assets/javascript/ folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM