简体   繁体   中英

Rails Jquery doesn't work on other pages

I believe jQuery doesn't work on other pages than the one you just installed. For example, when I type localhost:3000/, in the '/' directory all jQuery works. But when I click to a link created by Rails as

<%= link_to "Example Link", news_path %>

The page correctly loads, but the jQuery doesn't work. My jQuery codes are as stated:

$(function() {
  console.log( "pageloaded" );
  ....
  $('.up').click(function(){
    .....
  });
});

In Rails 4 turbolinks is active by default.
That means, that $(document).ready() is not executed, when you load a new page.

turbolink fires a new event page:load . You can use this to run your javascript code:

$(document).on('page:load', your_start_function);

There is an excelent rails cast on turbolinks

https://github.com/kossnocorp/jquery.turbolinks

This gem binds jQuery.ready function with Turbolinks listen event page:load, therefore the solution is supposed to be solved if you are using Turbolinks with Rails 4

You need gem 'jquery-rails' in your Gemfile (then bundle install if you're using bundler)

Once that's done, you need to require it in your application.js file:

//= require jquery

Last, you need to ensure that the application.js file is loaded as part of the application template. In application.html.erb you should have the following:

<%= javascript_include_tag "application" %>

I believe that this is all there by default in a Rails install so if you have removed any of these settings you'll need to add them back to get it to work.

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