【问题标题】:Simple Rails App - Uncaught ReferenceError: $ is not defined简单的 Rails 应用程序 - 未捕获的 ReferenceError:$ 未定义
【发布时间】:2021-01-27 11:39:57
【问题描述】:

我正在学习如何构建一个简单的 Rails 应用程序,但在将 JQuery 加载到应用程序中时遇到了一些问题。我收到“未捕获的 ReferenceError:$ 未定义”的控制台错误,但我不确定它为什么不起作用。任何帮助将不胜感激!我觉得我可能会丢失一些 js 文件,因为当我启动 rails 应用程序时,我的资产中没有“javascripts”目录,我不得不手动创建一个 - 不确定这是否正常。

这里也是我的仓库的链接:https://github.com/scottlandes1217/Hubbubb

应用程序.js

//= require jquery
//= require jquery_ujs
//= require popper
//= require_tree .
//= require bootstrap
//= require bootstrap-sprockets

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Hubbubb</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all' %>
    <%= javascript_include_tag 'application' %>
  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="col-12">
          <%= render partial: 'shared/navigation_bar' %>
          <div class="my-3">
            <%= yield %>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

forum_channel.js

$(function() {
  $('[data-channel-subscribe="room"]').each(function(index, element) {
    var $element = $(element),
        room_id = $element.data('room-id')
        messageTemplate = $('[data-role="message-template"]');

    $element.animate({ scrollTop: $element.prop("scrollHeight")}, 1000)        

    App.cable.subscriptions.create(
      {
        channel: "ForumChannel",
        forun: forum_id
      },
      {
        received: function(data) {
          var content = messageTemplate.children().clone(true, true);
          content.find('[data-role="user-avatar"]').attr('src', data.user_avatar_url);
          content.find('[data-role="message-text"]').text(data.message);
          content.find('[data-role="message-date"]').text(data.updated_at);
          $element.append(content);
          $element.animate({ scrollTop: $element.prop("scrollHeight")}, 1000);
        }
      }
    );
  });
});

再次感谢!

【问题讨论】:

  • 您的application.js 似乎只是一堆cmets ... jquery 是如何加载的?你的forum_channel.js 是如何加载的? forum_channel.js 是在加载 jquery 之后加载的吗?
  • 你能检查浏览器的源代码视图,特别是包含的
  • @JaromandaX 我相信这就是 application.js 的工作方式,但我确实尝试取消注释它们并且我得到了相同的结果。
  • 哦,对了...导轨...
  • @ChrisG 这是我的控制台视图和它正在加载的任何资产的截屏视频。我根本没有看到任何 Jquery screencast.com/t/bE64O6z3NU

标签: javascript jquery ruby-on-rails redis rubygems


【解决方案1】:

感谢大家的帮助 - 看起来我需要使用 yarn 通过 webpack 安装 jQuery。我使用的很多学习文档根本没有提到这样的东西。以正确的方式安装 Jquery 并将我的文件添加到正确的目录后,现在似乎正在加载 jQuery。我现在遇到了一个单独的问题,但我会发布一个单独的问题。

再次感谢大家!

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 2019-11-05
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多