[英]how to call js function from application.js in rails4 view
我试图以一种视图的方式调用我在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>
确保您的view / layout中包含application.js。 检查Chrome / Firefox控制台也是个好主意-您下载了此文件吗?该文件的内容是什么?
如果您看到浏览器已加载此文件和功能,请尝试在JS控制台中调用。 如果工作正常,则可能是您认为调用此函数为时过早。 在这些情况下,最简单的解决方法是(确保先加载DOM):
<script>
$(function() { autoFill(<%= @users %>) });
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.