【问题标题】:Rails and jQuery not working sometimesRails 和 jQuery 有时不工作
【发布时间】:2015-04-06 04:20:08
【问题描述】:

使用 rails 4 和 jQuery,但我似乎与两个函数有轻微的冲突。

第一个功能是滚动到顶部功能。

$(window).scroll(function(){
    if ($(this).offset().top > 600) {
        $('.scrollToTop').fadeIn(500);
    } else {
        $('.scrollToTop').fadeOut(500);
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},800);
    return false;
});

另一个是嵌套属性(RailsCast Tutorial)函数。

$(function() {
      $("form").on("click", ".remove_fields", function(event) {
        $(this).prev("input[type=hidden]").val("1");
        $(this).closest("fieldset").hide();
        return event.preventDefault();
      });
      return $("form").on("click", ".add_fields", function(event) {
        var regexp, time;
        regexp = void 0;
        time = void 0;
        time = new Date().getTime();
        regexp = new RegExp($(this).data("id"), "g");
        $(this).before($(this).data("fields").replace(regexp, time));
        return event.preventDefault();
      });
    });

现在一个有效,而另一个无效,我不确定是什么问题。如果我剪切并重新粘贴嵌套属性 jQuery,它可以工作,但如果我单击滚动到它就不起作用。

我是 jQuery 新手,所以我不确定是否会出现各种冲突。

Application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    按照此 gem https://github.com/kossnocorp/jquery.turbolinks 的步骤操作,但不要向下移动 //= 需要 turbolinks,只需将其完全删除即可。

    【讨论】:

      【解决方案2】:

      您应该使用jquery-turbolinks gem。

      gem 'jquery-turbolinks' 添加到您的 Gemfile 中,然后运行 ​​bundle install

      然后修改你的application.js文件

      //= require jquery
      //= require jquery.turbolinks
      //= require jquery_ujs
      //
      // ... your other scripts here ...
      //
      //= require turbolinks
      

      【讨论】:

        【解决方案3】:

        首先,安装jquery-turbolinks gem。然后,不要忘记将包含的 Javascript 文件从 application.html.erb 的正文末尾移动到其 <head>

        如果您出于速度优化的原因将应用程序 javascript 链接放在页脚中,则需要将其移动到标签中,以便它在标签中的内容之前加载。这个解决方案对我有用。

        【讨论】:

          猜你喜欢
          • 2018-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-27
          • 1970-01-01
          • 2011-04-28
          • 2019-04-01
          相关资源
          最近更新 更多