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

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

问题描述

我创建了一个 Rails 4 应用程序,并为图像弹出效果添加了fancybox 库.它工作正常,但仅当页面正在刷新时.如果用户没有刷新页面,则 jquery 根本不起作用.我也尝试使用小型 jquery 方法对其进行测试,但所有这些都只能在页面刷新后才能工作.我也在使用 Twitter 引导程序.

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.

我的 assets/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

你应该没事了.

仅供参考:您实际上并不需要使用 turbolinks,但它很有用,并且通过避免整页刷新来加快请求速度.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天全站免登陆