[英]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.