Rails 6:未捕获的引用错误 - $ 未定义

Rails 6: Uncaught Reference Error - $ is not defined

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

$(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)
Uncaught ReferenceError: $ is not defined

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

查看gem文件中是否添加了jquerygem

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

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

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