我试图在我的一个视图中调用我在application.js中编写的js函数,但由于某种原因,我这样做的方式不起作用
我的视图是一个带有引导模式的表单。我的模态有一个输入字段,我想使用ruby数组作为源
执行自动完成 <div>
<%@users = User.all.pluck(:email)%>
<script>
<%= "autoFill(@users)" %>
</script>
<% @users.each do |user| %>
<p><%= user%></p>
<% end %>
</div>
<div class="row">
<%= form_for(@note) do |f| %>
<% if @note.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@note.errors.count, "error") %> prohibited this note from being saved:</h2>
<ul>
<% @note.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>
<% end %>
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<input id="emails"></input>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
我在application.js中的方法是(目前应该自动完成)
var autoFill = function(emailsList){
var listOfKeys = emailsList;
$("#emails").autocomplete({
minLength: 2,
source: listOfKeys,
select: function(event,ui) {
if (event.keyCode ==13){ // prevent the trigger of the enter listner from the autocomplete selection.
return false; // clear the field and cancel the focus on the autocomplete.
}
return false; // clear the field and cancel the focus on the autocomplete.
}
});
// set enter listner
$("#emails").keyup(function(event) {
if (event.keyCode == 13) {
$(emails).autocomplete("close");
}
});
};
我尝试按照以下方式将视图添加到方法中,这是我在这里的几个帖子中找到的
<script>
<%= "autoFill(@users)" %>
</script>
答案 0 :(得分:0)
确保您的视图/布局中包含您的application.js。 检查Chrome / Firefox控制台也是一个好主意 - 您是否已下载此文件以及该文件的内容是什么?
如果您看到浏览器已加载此文件和函数,请尝试在JS控制台中调用。如果它工作正常,那么也许你认为太早调用这个函数。在这些情况下,最简单的修复是(确保首先加载DOM):
<script>
$(function() { autoFill(<%= @users %>) });
</script>