简体   繁体   English

Rails Jquery不适用于其他页面

[英]Rails Jquery doesn't work on other pages

I believe jQuery doesn't work on other pages than the one you just installed. 我相信jQuery不能在你刚刚安装的页面上工作。 For example, when I type localhost:3000/, in the '/' directory all jQuery works. 例如,当我键入localhost:3000 /时,在'/'目录中所有jQuery都可以工作。 But when I click to a link created by Rails as 但是当我点击Rails创建的链接时

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

The page correctly loads, but the jQuery doesn't work. 页面正确加载,但jQuery不起作用。 My jQuery codes are as stated: 我的jQuery代码如下所述:

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

In Rails 4 turbolinks is active by default. 在Rails 4中,默认情况下turbolinks处于活动状态。
That means, that $(document).ready() is not executed, when you load a new page. 这意味着,当您加载新页面时, $(document).ready()不会被执行。

turbolink fires a new event page:load . turbolink触发一个新的事件page:load You can use this to run your javascript code: 您可以使用它来运行您的JavaScript代码:

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

There is an excelent rails cast on turbolinks 在turbolinks上有一个优秀的轨道

https://github.com/kossnocorp/jquery.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 这个gem将jQuery.ready函数绑定到Turbolinks监听事件页面:load,因此如果你使用Turbolinks和Rails 4,那么解决方案应该会被解决

You need gem 'jquery-rails' in your Gemfile (then bundle install if you're using bundler) 您需要在Gemfile中使用gem'jquery gem 'jquery-rails' (如果您使用的是Bundler,则需要捆绑安装)

Once that's done, you need to require it in your application.js file: 完成后,您需要在application.js文件中要求它:

//= require jquery

Last, you need to ensure that the application.js file is loaded as part of the application template. 最后,您需要确保将application.js文件作为应用程序模板的一部分加载。 In application.html.erb you should have the following: application.html.erb您应该具有以下内容:

<%= 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. 我相信在Rails安装中默认情况下就是这样,所以如果您已经删除了这些设置中的任何一个,则需要将它们添加回来以使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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