【问题标题】:Rails 6: Uncaught Reference Error - $ is not definedRails 6:未捕获的引用错误 - $ 未定义
【发布时间】:2019-12-03 21:45:02
【问题描述】:

我正在尝试让语义 UI 按钮在 Rails 6 中使用 Javascript 工作。但是,我的代码都没有正常工作。代码如下所示:

$(document).on('turbolinks:load', function() {
   $('.message .close').on('click', function() {
   $(this).closest('.message').transition('fade');
   })
;
})

我得到的错误是:Uncaught ReferenceError: $ is not defined。

我的应用程序 JS 文件如下所示:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
// Loads all Semantic javascripts
//= require jquery
//= require semantic-ui
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

【问题讨论】:

    标签: javascript jquery ruby-on-rails semantic-ui ruby-on-rails-6


    【解决方案1】:
    Uncaught ReferenceError: $ is not defined
    

    此错误引用 $ 尚未声明,这最终表示 jquery 未正确加载到页面中

    检查gemfile中是否添加了jquery gem

    另外,试试是否使用jQuery作为标识符而不是$

    【讨论】:

    • jquery 在 gemfile 中!使用 jQuery 响应相同的错误,将 $ 替换为 jQuery:/
    • 抱歉回复晚了。如果您的问题还没有解决,那么如果您可以发布以下的 sn-ps 或屏幕截图,您可以获得更好的帮助。 1、gemfile 2、application.js 3、带有标题的主布局erb文件4、使用jquery sn-p的文件5、控制台日志
    【解决方案2】:

    在您的 html 页面中添加 jquery 支持文件。

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    

    【讨论】:

    • 这会将一些东西从 Webpacker 环境中移除,并不能真正解决所提出的问题。
    猜你喜欢
    • 2013-10-27
    • 2011-09-25
    • 2021-11-01
    • 2017-11-22
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多