Where should I place my jQuery code in my Ruby on Rails applications?

后端 未结 1 847
后悔当初
后悔当初 2021-01-13 18:44

I\'m partially new to RoR and fairly new to jQuery. Currently, I have a working RoR site as a learning platform. I want to include some jQuery basic features to expand my le

1条回答
  •  抹茶落季
    2021-01-13 19:20

    You should make a file within app/assets/javascripts/ name after the controller that the view is associated with, for example for a controller named home it would be: app/assets/javascripts/home.js then within your application.js file include it into the asset pipeline as so:

    //= require jquery
    //= require jquery_ujs
    //= require bootstrap
    //= require home
    

    But since you already have //=require tree . the above modification to application.js should not be necessary but I would suggest doing it as above and include all of your files singularly so that you can have more control over when your JS is included.

    Edit: Also, I would suggest changing the binding you are using from an ID to a Class incase you want to reuse this functionality.

    For Testing purposes to see if the JS is being executed you can add something like:

    $(document).ready(function(){
        $('#present').mouseenter(function(){
            alert("MouseEnter!"); // This will create an alert box
            console.log("MouseEnter!"); // This will log to the JS console on your browser which is a bit nicer to read than alerts, you do not need both, just preference
            $(this).fadeIn('fast',1);
        }
        $('#present').mouseleave(function(){
            alert("MouseLeave!"); // This will create an alert box
            console.log("MouseLeave!");
            $(this).fadeIn('fast',0.5);
        }
    });
    

    This is only to test the JS quick, you should never leave these in your code of course.

    Also, after taking a second look at the JS you may want to try something like this:

    $(document).ready(function(){
        $('#present').mouseenter(function(){
            $(this).fadeIn('fast',1);
        }).mouseleave(function(){
            $(this).fadeIn('fast',0.5);
        });
    });
    

    note the closing );

    0 讨论(0)
提交回复
热议问题