【发布时间】:2016-11-04 14:29:34
【问题描述】:
实际上,我想在我的 rails 应用程序中执行 javascript 代码。
我在“app/assets/javascripts”中创建了 custom.js 新文件。
custom.js
$( document ).ready(function() {
$("div#test").hide();
$("a").click(function(event) {
event.preventDefault();
$("div#test").fadeToggle();
});
});
我还添加了,//= 在 application.js 文件中需要自定义,但代码并没有从一开始就隐藏。
应用程序.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require nicetitle
//= require custom
index.html.erb
<a href="#" class="toggle-formed" style="float: right;" >Search</a>
<div id="sample" class="<%= @xvaziris_data.present? ? 'hidden' : '' %>">
<%= form_tag xvaziris_path, method: 'get', class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
<% if @xvaziris.empty? %>
<center><p><em>No results found for.</em></p></center>
<% end %>
</div>
general.scss
.hidden {
display: none;
}
上面的 custom.js 代码,当我将 index.html.erb 放在 javascript 脚本标记下时,它可以正常工作。但我不想在所有其他控制器/索引中重复自己,因为导轨遵循 DRY 原则,即不要重复自己。
搜索.js
$(document).on('page:change', function () {
$("div#sample").hide();
// | === HERE
$("a.toggle-formed").click(function(event) {
event.preventDefault();
$("div#sample").fadeToggle();
});
});
欢迎提出任何建议。
提前谢谢你。
【问题讨论】:
-
您的 custom.js 在您放入 application.js 时在您的页面中可用
-
感谢您的回复。 custom.js 文件位于“app/assets/javascripts”下,它是一个单独的文件。
-
是的,但必须用
<script>标签括起来 -
我认为您不需要
//= require custom将 custom.js 添加到 javascripts/ 中就足够了。我自己对此进行了测试,它在我的构建中运行良好。 -
添加后是否尝试重启服务器