为什么 jQuery 在我的 rails 5 应用程序中不起作用?

Why is jQuery not working in my rails 5 app?

我正在尝试在我的新 Rails5 应用程序中编写我的第一个 js 代码,但似乎无法使 Jquery 工作,我猜这是一个 config/environment 问题,但尽管我进行了所有搜索和配置更改,但我似乎无法得到它 运行。谁能看出我做错了什么?:

gemfile;

 # Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'

application.html.erb;

<title>MyEngine</title>
<!-- Gon::Base.render_data -->
<%= Gon::Base.render_data %>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

new.html.erb;

<%= link_to 'Remove Employee', '#', id: 'hide-employee' %>

quotes.coffee;

$(document).on "page:change", ->
    $('#hide-employee').click ->
        alert "Clicked!"

点击时没有提示。没有错误,服务器 运行 和页面呈现正常,控制台中没有任何内容。

感谢您的帮助。

page:change 事件在 turbolinks-classic 中定义。这个版本现在已经弃用了,你可以自己看看。

相反,您可以使用 turbolinks:load or turbolinks:render or turbolinks:before-render

请尝试使用 turbolinks:load。

$(document).on 'turbolinks:load', ->
  $('#hide-employee').click ->
    alert 'Clicked!'

确保您 app/assets/javascripts/application.js 包含:

//= require jquery
//= require jquery-ujs

注意:如果您使用的是 Rails 5.1,则可以省略 //= require jquery_ujs 而使用 //= require rails-ujs

此外,请考虑彻底删除 turbolinks。这样做解决的资产管道问题比我计算的还要多。我有一种感觉,它并没有为你提供太多价值。 :-)

删除 turbolinks:

  1. Gemfile$ bundle.
  2. 中删除 turbolinks
  3. app/assets/javascripts/application.js
  4. 中删除 //= require turbolinks
  5. app/views/layouts/application.html.erb.
  6. 中删除两个 "data-turbolinks-track" => true 哈希值

对于那些因为 Rails 5.1 而来到这里的人,jQuery 不再是默认依赖项 。来自 release notes:

jQuery was required by default in earlier versions of Rails to provide features like data-remote, data-confirm and other parts of Rails' Unobtrusive JavaScript offerings. It is no longer required, as the UJS has been rewritten to use plain, vanilla JavaScript. This code now ships inside of Action View as rails-ujs.

You can still use jQuery if needed, but it is no longer required by default.

要重新添加,请添加到 Gemfile:

gem 'jquery-rails'             # Use jquery as the JavaScript library

然后

$ bundle