我想在我的 Rails 应用程序中使用静态 javascript 文件而不使用 gem。我的 application.js
看起来像这样
//= require jquery
//= require bootstrap
//= require owl-carousel
//= require rails-ujs
我必须将所有 Js 文件添加到 javascript 文件夹中,而不使用任何使用 Assets 管道的 gem。 The final output that i want 。但在我的 Rails 应用程序中 javascript is not working or not loading 。我的 application.css.scss
如下所示:
@import "bootstrap";
@import "style";
@import "owl-carousel";
以及index.html.erb
的代码
<div class="app_screenshots_slides owl-carousel">
<div class="single-shot">
<%=image_tag("scr-img/1.png", alt: "")%>
</div>
<div class="single-shot">
<%=image_tag("scr-img/2.png", alt: "")%>
</div>
<div class="single-shot">
<%=image_tag("scr-img/3.png", alt: "")%>
</div>
<div class="single-shot">
<%=image_tag("scr-img/4.png", alt: "")%>
</div>
<div class="single-shot">
<%=image_tag("scr-img/1.png", alt: "")%>
</div>
<div class="single-shot">
<%=image_tag("scr-img/3.png", alt: "")%>
</div>
</div>
最佳答案
您的所有 JavaScript 实际上都已加载,但问题是您没有初始化 owl carousel 插件。只需添加
$(document).ready(function () {
$(".owl-carousel").owlCarousel();
});
在你的home/index.html.erb
的底部或者在你的相关js文件中使其工作。
编辑 - 修复您当前的设置
问题是你的插件在加载实际的 html 之前就已初始化。可能的修复方法是
1.更改
(function ($) {
'use strict';
// :: 1.0 Owl Carousel Active Code
if ($.fn.owlCarousel) {
$(".welcome_slides").owlCarousel({
items: 1,
loop: true,
autoplay: true,
smartSpeed: 1500,
nav: true,
navText: ["<i class='pe-7s-angle-left'</i>", "<i class='pe-7s-angle-right'</i>"]
});
$(".app_screenshots_slides").owlCarousel({
items: 1,
loop: true,
autoplay: true,
smartSpeed: 800,
margin: 30,
center: true,
dots: true,
responsive: {
0: {
items: 1
},
480: {
items: 3
},
992: {
items: 5
}
}
});
}
})(jQuery)
;
在assets/javascripts/owl-carousel.js
到
$(document).ready(function () {
if ($.fn.owlCarousel) {
$(".welcome_slides").owlCarousel({
items: 1,
loop: true,
autoplay: true,
smartSpeed: 1500,
nav: true,
navText: ["<i class='pe-7s-angle-left'</i>", "<i class='pe-7s-angle-right'</i>"]
});
$(".app_screenshots_slides").owlCarousel({
items: 1,
loop: true,
autoplay: true,
smartSpeed: 800,
margin: 30,
center: true,
dots: true,
responsive: {
0: {
items: 1
},
480: {
items: 3
},
992: {
items: 5
}
}
});
}
});
2. 移动您的javascript_include_tag
在你的application.html.erb
到页面底部,就在 </body>
之前
3. 将 owl carousel 初始化脚本从 owl-carousel.js
移出给您home/index.html.erb
希望这会有所帮助。
关于JavaScript 无法在 Rails 5 应用程序中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48008939/