使用未捕获的ReferenceError:未定义$

时间:2020-07-30 18:21:19

标签: javascript jquery ruby-on-rails asset-pipeline

在我的Rails 6项目中,我一直在尝试使用资产管道来使application.js使用jQuery和app/assets/javascript/event_index.js上的JavaScript文件,但两者均无法正常工作。加载网页时,我得到Uncaught ReferenceError: $ is not defined的信息,而单击内容时JavaScript代码没有任何作用。

我尝试过的事情:

  • this StackOverflow question的最高答案表明,我可以编写//=require events_index来获取events_index.js,但这无济于事
  • 我没有意识到我的//= require行必须在标题中。当我更改它时,它仍然没有帮助
  • 我跑了gem 'jquery-rails'
  • 我以前使用的是$(document).ready(),但显然是因为Rails 6使用了TurboLinks,它不再起作用了,所以我更改了它。

这是我的application.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.

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require events_index

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// 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)

$( document ).on('turbolinks:load', function() {
    console.log( "ready!" );
});

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

默认情况下,webpacker附带了Rails 6,您应该改为通过yarn安装jquery并通过webpacker加载它。参见How to add jquery third party plugin in rails 6 webpacker