在我的index.html.erb
文件中,我的表单成功地提交了Onchange。但是,这仅在我使用以表格之后放置的<script>
标签时起作用。为什么welcome.js
中的JS不运行?索引作为/welcome
路线加载。
# app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ace.min
//= require jquery.sortable
//= require chartkick
//= require hammer
//= require_tree .
外部JS文件
# app/assets/javascripts/welcome.js
$('.chart-radio-icon').change(function(){
$('#mega_form').submit();
});
查看
# views/welcome/index.html.erb
<%= form_tag mega_chart_path, id: 'mega_form', remote: true do %>
<%= radio_button_tag :metric_type, :followers_count, true, :class => 'chart-radio-icon'%>
<%= label_tag(:followers, 'Followers', :class => 'chart-label chart-label-social') %>
再次将JS放置在视图中的<script>
标签中,但不在外部。
编辑:
由于我们已经确定您的资产文件未包含在开发中。为了进行理智检查,请尝试此操作并重新启动您的服务器:
Rails.application.config.assets.precompile = %w( application.js application.css )
结束编辑
由于您使用的是require_tree .
,并且由于welcome.js
文件位于app/assets/javascripts
中,因此它将包含在应用程序中的所有页面中。看这里。我认为问题在于,在页面加载上,事件侦听器没有被分配给DOM元素。尝试将您的JS代码包装在:
#app/assets/javascripts/welcome.js
$(document).ready(function(){
....
});