Dev*_*vin 5 jquery ruby-on-rails
我正在运行jQuery以app/assets/javascripts/ticket.js.coffee获取特定视图.每次我访问该页面时,浏览器都会出现此错误 - 在线任何地方都没有提到此错误.
(localhost:3000 /门票/新):
SyntaxError: unexpected POST_IF
Extracted source (around line #6):
3: <head>
4: <title>Ops2</title>
5: <%= stylesheet_link_tag "application", :media => "all" %>
6: <%= javascript_include_tag "application" %>
7: <%= csrf_meta_tags %>
8: </head>
9: <body>
Run Code Online (Sandbox Code Playgroud)
抛出错误的页面文件 -
app/views/tickets/_form.html.erb:
<%= form_for(@ticket) do |f| %>
<% if @ticket.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@ticket.errors.count, "error") %> prohibited this ticket from being saved:</h2>
<ul>
<% @ticket.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :school_id %><br />
<%= f.collection_select :school_id, School.order(:name), :id, :name, include_blank: true%>
</div>
<div class="field">
<%= f.label :location_id %><br />
<%= f.grouped_collection_select :location_id, School.order(:name), :locations, :name, :id, :name, include_blank: true%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Run Code Online (Sandbox Code Playgroud)
app/assets/javascripts/application.js包含:
//= require jquery
//= require jquery_ujs
//= require_tree .
Run Code Online (Sandbox Code Playgroud)
使用jQuery的Coffeescript文件 -
app/assets/javascripts/tickets.js.coffee:
$ ->
$('#ticket_location_id').parent().hide()
locations = $('#ticket_location_id').html()
$('#ticket_school_id').change ->
school = $('#ticket_school_id :selected').text()
options = $(locations).filter("optgroup[label='#{school}']").html()
if options
$('#ticket_location_id').html(options)
$('#ticket_location_id').parent().show()
else
$('#ticket_location_id').empty
$('#ticket_location_id').parent().hide()
Run Code Online (Sandbox Code Playgroud)
通过缩进if / else我的咖啡脚本中的语句来解决POST_IF错误!(详见下面的答案)没有错误,页面加载!
你错过了你的if陈述缩进.缩进在CoffeeScript中至关重要.
这个...
if options
$('#ticket_location_id').html(options)
$('#ticket_location_id').parent().show()
else
$('#ticket_location_id').empty
$('#ticket_location_id').parent().hide()
Run Code Online (Sandbox Code Playgroud)
... 需要这样,领先的缩进不是可选的:
if options
$('#ticket_location_id').html(options)
$('#ticket_location_id').parent().show()
else
$('#ticket_location_id').empty
$('#ticket_location_id').parent().hide()
Run Code Online (Sandbox Code Playgroud)