CoffeeScript 仅在 Rails 应用中重新加载页面后才有效

CoffeScript works only after page reload in Rails app

我有两个select,第二个根据第一个的值变化。我使用 CoffeScript。

  <%= f.collection_select :type, RequestType.order(:typeName), :id, :typeName, 
{include_blank:true }, {:class => "types"} %>
   
 <%= f.grouped_collection_select :subtype, RequestType.order(:typeName), 
:RequestSubTypes, :typeName, :request_type_id, :subTypeName, 
{include_blank:true},
{:class => "subTypes" }  %>
当 select 1 更改第二个选项时重新加载(第二个 select 中的选项取决于第一个 select 中的选项。 这是我的 CoffeScript 代码:

jQuery ->
 subTypes = $(".subTypes").html()
 $(".subTypes").parent().hide()
 $(".types").change ->
  type = $(".types :selected").text()
  options = $(subTypes).filter("optgroup[label='#{type}']").html()
  if options  
   $(".subTypes").html(options)
   $(".subTypes").parent().show()
  else
   $(".subTypes").empty()
   $(".subTypes").parent().hide()
它有效,但只有在我重新加载页面之后。如果我从 general link_to 访问页面,那么 CoffeScript 似乎无法正常工作。因此,当导航到该页面时,我总是必须重新加载页面。使用 link_to 的页面导航看起来像 ajax,但我没有使用 ajax。 这是我的 link_to:

<%= link_to "link", new_request_path %>

我相信您正在使用 turbolinks。这就是你的 jquery bootstrap 在你最初访问的页面上执行一次并且不会与其他页面的 DOM 挂钩的方式,因此你的回调不会赶上。

你有几个选项来处理它。

  1. 在布局头的 javascript_tag 上使用属性 data-turbolinks-track='false'。这样 js 文件将在每个页面加载时与主体一起加载和执行。

  2. 将整个 javascript_tag 调用移至 body 的底部。

  3. 使用jquery-turbolinksgem。