我正在尝试设置一个表单,以便当我点击enter时通过ajax提交。为此,我想触发在输入字段上按Enter键时提交的表单。但是,如果按下键的时间超过一秒钟,则Enter键的keyup事件将持续触发多次,这又会发送大量的ajax请求,从而导致浏览器崩溃。
我不知道为什么该事件持续触发多次。这是页面的视图:
<div class="page-content">
<div class="l-edit-header">
<h1>Edit</h1>
<div class="piece-header">
<%= image_tag @piece.user.avatar_url(:small), class: "avatar-small" %>
<div class="piece-header-info">
<h1><a href="<%= piece_path @piece %>"><%= @piece.title %></a></h1>
<em>
By <%= link_to @piece.user.username, user_path(@piece.user) %>
<%= @piece.created_at.strftime("%B %d, %Y") %>
</em>
</div>
</div>
</div>
<div class="l-edit-main">
<div class="piece-main">
<%= image_tag @piece.image_url %>
<p id="piece-description" class="piece-main-description"><%= @piece.description %></p>
<div class="piece-main-links">
<%= link_to "Delete", piece_path(@piece), method: :delete if current_user == @piece.user %>
</div>
</div>
</div>
<div class="l-edit-side">
<div class="form-container">
<%= form_tag piece_tags_path(@piece), id: "new_tag", remote: true do %>
<%= label_tag :new_tag, "New Tag"%>
<%= text_field_tag :tag, "", data: {autocomplete_source: tags_url}, placeholder: "Add a tag and press Enter" %>
<div id="tags" class="piece-tags">
<%= render partial: "tags/delete_tag_list", locals: {piece: @piece, method: :delete} %>
</div>
<% end %>
</div>
<div class="form-container">
<%= simple_form_for @piece do |f| %>
<%= f.association :category, include_blank: false %>
<%= f.input :published, as: :hidden, input_html: {value: true} %>
<%= f.input :title %>
<%= f.input :description %>
<div class="form-submit">
<%= f.button :submit, "Publish" %>
</div>
<% end %>
</div>
</div>
</div>
这是我尝试使用的标记形式的Javascript:
var tagReplace = {
init: function(){
//Replace "#tags" with new updated tags html on tag create
$("#new_tag").on("ajax:success", function(e, data, status, xhr){
$("#tags").html(data);
tagReplace.init();
$("#tag").val("");
});
//Replace "#tags" with new updated tags html on teg delete
$("#tags a[data-remote]").on("ajax:success", function(e, data, status, xhr){
$("#tags").html(data);
tagReplace.init();
});
$("#new_tag").on("keydown", function(e){
if (e.which == 13){
event.preventDefault();
}
});
$("#tag").on("keyup", function(e){
if (e.which == 13){
$("#new_tag").submit();
console.log("pressed enter on new tag");
}
});
},
getTags: function(){
$.get( $("#tag").data("autocomplete-source"), tagReplace.initAutocomplete);
},
initAutocomplete: function(tagsArray){
$("#tag").autocomplete({
source: tagsArray
});
}
};
//Initalize
$(document).on('ready page:load', function () {
tagReplace.init();
});
如您所见,我阻止了在窗体上按下return键的默认行为,并添加了console.log
来计算事件被触发的次数。
我以为这可能与我使用turbolinks有关,但我似乎无法弄清楚原因。
我如何确保每次按下Enter键仅触发一次事件?当我按enter。
时,JavaScript使浏览器崩溃。您正在调用tagReplace.init();自身内部有2次,并且正如@Dezl在他的answer related to this topic中所述,“如果将委托的事件绑定到文档,请确保将它们附加到ready函数之外,否则它们将在每个page:load事件上反弹(导致同一功能多次运行。“