$(document).ready(function() {
$('#client-select2').select2();
});
如果我将上面的代码放在 application.js 中,它不会响应,但如果我将它放在 _form.html.erb 文件中,它会响应。有谁知道这是为什么吗?
View /订单/_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' %>
最佳答案
原因可能是 select2 和/或 jQuery 包含在 application.js 之后,
例如,如果订单是:
//=require_self
//=require select2
//=require jquery
jquery/select2 函数在 application.js 中将不可用,因为 application.js 之前已包含。
关于JavaScript Rails 代码无法在 application.js 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23943562/