JavaScript Rails代码在application.js中不起作用

时间:2014-05-29 21:46:54

标签: javascript ruby-on-rails ruby-on-rails-4

  $(document).ready(function() { 
    $('#client-select2').select2();
   });

如果我将上面的代码放在application.js上,它就不会响应,但是如果我将它放在_form.html.erb文件中,它就会响应。谁知道为什么会这样?

视图/命令/ _form.html.erb

<script type="text/javascript">
  $(document).ready(function() { 
    $('#client-select2').select2();
   });

</script>

<%= simple_form_for(@order) do |f| %>
  <%= f.error_notification %>
    <%= f.input :code %>
    <%= f.association :client, collection: Client.all, label_method: :name, value_method: :id, prompt: "Choose a Client", required: true, input_html: { id: 'client-select2' } %>
    <%= f.submit %>
<% end %>

application.html.erb有

<%= javascript_include_tag 'application' %>

1 个答案:

答案 0 :(得分:2)

原因可能是你的application.js,

之后包含了select2和/或jQuery

例如,如果订单是:

//=require_self
//=require select2
//=require jquery

jquery / select2函数在application.js中不可用,因为之前包含了application.js.