【问题标题】:Using Uncaught ReferenceError: $ is not defined使用未捕获的 ReferenceError: $ 未定义
【发布时间】:2020-11-20 13:09:52
【问题描述】:

在我的 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!" );
});

感谢您的帮助!

【问题讨论】:

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


【解决方案1】:

Rails 6 默认带有 webpacker,你应该通过 yarn add 安装 jquery 并通过 webpacker 加载它。见How to add jquery third party plugin in rails 6 webpacker

【讨论】:

    猜你喜欢
    • 2023-01-23
    • 2016-11-03
    • 2011-01-05
    • 2016-01-02
    • 2013-10-06
    • 2016-12-17
    • 1970-01-01
    相关资源
    最近更新 更多