Rails App中的JS仅在第一次加载 [英] JS in Rails App only loads the first time

查看:109
本文介绍了Rails App中的JS仅在第一次加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用主页上的某些链接上使用了淡入淡出效果。这是由一些JQuery实现的:

I am using a fade effect on some links on my applications home page. This is being accomplished by some JQuery:

javascripts / pages.js

$(document).ready(function() {
    $('.home_tile_text').hide().removeClass('text').addClass('text-js');
    $('.home_tile_overlay').hide().removeClass('overlay').addClass('overlay-js');

    $('.home_tile').mouseenter(function(){
        $(this).find('.text-js').finish().hide().fadeIn();
         $(this).find('.overlay-js').finish().hide().fadeIn();
    });
    $('.home_tile').mouseleave(function(){
        $(this).find('.text-js').finish().show().fadeOut();
         $(this).find('.overlay-js').finish().show().fadeOut();
    });
});

当我第一次启动应用程序时,这一切都很有效。但是,如果我离开主页,当我回来时,淡入淡出效果在我刷新页面之前不再有效。任何想法?

This all works great when I fire up the app for the first time. However, if I navigate away from the home page, when I come back, the fade effect no longer works until I "refresh" the page. Any ideas?

推荐答案

这可能是因为Rails 4的新功能 Turbolinks 。 Turbolinks仅通过更新更改页面的部分来减少来自客户端的服务器请求。这意味着 document.ready (或jQuery中的 $(document).ready )不会再次被调用加载新页面。

This is probably because of Rails 4's new feature Turbolinks. Turbolinks reduces server requests from the client by only updating the parts of the page that change. This means that document.ready (or $(document).ready in jQuery) doesn't get called again when loading new pages.

一个解决方案就是删除gemfile中的 gem'turbolinks'和<$ c在您的application.js中需要turbolinks ,从而禁用turbolinks,但更简单的解决方法是在应用程序中添加 require jquery.turbolinks .js文件,其中包含一个turbolinks脚本,通过在每个turbolinks调用上调用 $(document).ready 来修补问题。

One solutions is to just remove the gem 'turbolinks' in your gemfile and require turbolinks in your application.js, thereby disabling turbolinks, but an easier fix is to just add require jquery.turbolinks in the application.js file which includes a turbolinks script that patches the problem by calling $(document).ready on every turbolinks call.

有关更多信息,请参阅turbolinks自述文件中的 jQuery部分

For more, refer to the jQuery section in the turbolinks readme.

这篇关于Rails App中的JS仅在第一次加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆