只有在Rails应用程序中重新加载页面后,CoffeScript才能运行

yer*_*syl 1 javascript jquery ruby-on-rails coffeescript

我有两个选择,第二个根据第一个的值而改变.我使用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" }  %>
Run Code Online (Sandbox Code Playgroud)
当select 1更改时,第二个选项中的选项会重新加载(第二个选项中的选项取决于第一个选项中选择的选项.这是我的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()
Run Code Online (Sandbox Code Playgroud)
它工作,但只有在我重新加载页面后.如果我从一般link_to访问页面,似乎CoffeScript无法正常工作.因此,当导航到该页面时,我总是必须重新加载页面.使用link_to导航到页面看起来像ajax,但我没有使用ajax.这是我的link_to:

<%= link_to "link", new_request_path %>
Run Code Online (Sandbox Code Playgroud)

Alm*_*ron 5

我相信你正在使用turbolinks.这是你的jquery引导程序在你最初访问的页面上执行一次并且没有与其他页面的DOM挂钩的方式,因为你的回调没有赶上.

你有几个选择来处理它.

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

  2. 将整个javascript_tag通话移至您的底部body.

  3. 使用jquery-turbolinks宝石.