jQuery仅在Rails 4应用程序中的页面刷新时加载 [英] JQuery gets loaded only on page refresh in Rails 4 application

查看:69
本文介绍了jQuery仅在Rails 4应用程序中的页面刷新时加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了Rails 4应用程序,并添加了fancybox库以实现图像弹出效果.它工作正常,但仅在刷新页面时有效.如果用户未刷新页面,则jQuery根本不起作用.我也尝试使用小型jquery方法对其进行测试,但所有方法只有在页面刷新后才能工作.我也在使用Twitter Bootstrap.

I have created a Rails 4 application and have added fancybox library for an image popup effect. It works fine but only when the page is being refreshed. If the page is not refreshed by the user then the jquery does not work at all. I tried testing it with small jquery methods also but all work only after page refresh. I am also using twitter bootstrap.

我的资产/application.js文件:

My assets/application.js file :

//= require jquery
//= require jquery_ujs
//= require fancybox
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .


$(document).ready(function() {
  $(".fancybox").fancybox();
    $("#hand").click(function(){
     if($("#check6").is(':visible'))
     {
      $("#check6").hide();
      }
     else
     {
      $("#check6").show();
      }
    });
});

推荐答案

好的,我想我理解您的问题足以提供答案了.使用Turbolinks的事情是,大多数绑定到文档就绪事件的插件和库都停止工作,因为Turbolinks阻止了浏览器重新加载页面.有解决这些问题的技巧,但是最简单的解决方法是使用 jquery.turbolinks .

Okay, I think I understand your problem enough to provide an answer. The thing about using turbolinks is that most plugins and libraries that bind to the document ready event stop working, since turbolinks prevents the browser from reloading the page. There are tricks to fix those issues, but the easiest way to fix it is to use jquery.turbolinks.

要使用它,只需将其添加到您的Gemfile:

To use it, just add this to your Gemfile:

gem 'jquery-turbolinks'

,并将其保存到您的assets/javascripts/application.js文件中:

and this to your assets/javascripts/application.js file:

//= require jquery.turbolinks

你应该很好.

仅供参考:您实际上并不需要使用Turbolink,但它很有用,并且可以避免刷新整个页面,从而加快了请求的速度. Turbolinks通过AJAX获取您单击的链接的内容,并将其呈现在同一页面上,从而消除了重新加载资产(JS和CSS)的开销.尝试使您的页面使用它.使用上一段中的库,我没有遇到任何实际问题.页面上的CSS和JS越多,使用Turbolinks带来的改进就越大.

FYI: You don't really need to use turbolinks, but it's useful and it makes requests faster by avoiding a full page refresh. Turbolinks fetches the contents of the link you clicked via AJAX and renders it on the same page, thus eliminating the overhead of reloading assets (JS and CSS). Try to make your page work with it. Using the library in the previous paragraph I've had no real issues. The more CSS and JS you have on your page, the bigger the improvement you get by using turbolinks.

这篇关于jQuery仅在Rails 4应用程序中的页面刷新时加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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