【问题标题】:jQuery conflict on RailsRails 上的 jQuery 冲突
【发布时间】:2019-06-26 06:56:36
【问题描述】:

我的application.js

//= require rails-ujs
//= require jquery
//= require activestorage
//= require turbolinks
//= require bootstrap-sprockets
//= require flatpickr.min
//= require_tree .

我的Gemfile

gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'bootstrap-sass'
gem 'jquery-rails'

如果我 我只是这样离开我的应用程序,我所有的 jQuery 都可以正常工作。但我也需要

<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"</script>
</head>

在我的 application.html.erb 上,因为我使用的是 Bootstrap 4。

因此,使用这种配置,我的 jQuery 遇到了很多问题,比如

$(...).flatpickr 不是函数

有没有办法避免这些冲突? 我想那是因为我在我的应用程序中包含了多个 jQueries

如果我删除 //= require jquery,所有与 Bootstrap 相关的 jQuery 都可以工作,但我的自定义脚本不会。
如果我删除&lt;script src="https://code.jquery.com/jquery-3.3.1.min.js"&lt;/script&gt;,我的脚本会起作用,但所有与 Bootstrap 相关的脚本都不会(如汉堡导航栏或类似物)。

【问题讨论】:

  • Bootstrap-sass 适用于 bootstrap 3。您是从 bootstrap-sass gem 顶部的 cdn 导入 bootstrap4 吗?
  • @GiorgioZanni 如果我删除了bootstrap-sass gem,我会得到一个Sass::SyntaxError -&gt; File to import not found or unreadable: bootstrap.
  • 我的意思是问你为什么在导入 bootstrap 3 gem 时说你使用的是 bootstrap 4?尝试gem 'bootstrap', '~&gt; 4.2.1' 而不是bootstrap-sass。在任何情况下,您都不需要在 &lt;head&gt; 标记中包含 jquery。如果您使用的是 bootstrap 的 gem,它将与 jquery gem 一起使用,否则,如果您使用的是 CDN,则需要将 jquery 的 cdn 放在关闭 &lt;/body&gt; 标记之前。

标签: jquery ruby-on-rails bootstrap-4 ruby-on-rails-5.1 jquery-rails


【解决方案1】:

以下是将引导程序 4 添加到您的 rails 5 应用程序的步骤这里是指向 rubygemsgithub 页面的链接。

第 1 步:将 bootstrap 和 jquery-rails 添加到您的 Gemfile(确保 sprockets-rails 至少为 v2.3.2)

gem 'bootstrap', '~> 4.2.1'
gem 'jquery-rails'

第 2 步:将 Bootstrap 依赖项和 Bootstrap 添加到您的 application.js

//= require jquery3
//= require popper
//= require bootstrap

您不需要在视图上指定 jquery 的 cdn,这是行 //= require jquery3.并删除您的 bootstrap-sass 依赖项,即bootstrap 3

注意:需要注意的是,您需要使用 //= require jquery3

来要求 jquery3

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    相关资源
    最近更新 更多