我的网站上有一个表单,可以将图片上传到图库。 我希望用户能够添加和删除表单字段,并按照这个很棒的教程来实现:http://davidlesches.com/blog/rails-nested-forms-using-jquery-and-simpleform
我的javascript看起来像这样
$(document).ready(function(){
if($(".duplicatable-nested-form").size() > 0){
nestedForm = $(".duplicatable-nested-form").last().clone();
}
$(".duplicate-nested-form").click(function(event){
event.preventDefault();
lastNestedForm = $(".duplicatable-nested-form").last();
count = $(lastNestedForm).find("input").attr("id");
console.log(count);
newNestedForm = $(nestedForm);
formsOnPage = $(".duplicatable-nested-form").size();
$(newNestedForm).find("label").each(function(){
oldLabel = $(this).attr("for");
newLabel = oldLabel.replace(new RegExp(/_[0-9]+_/), "_" + formsOnPage + "_");
$(this).attr("for", newLabel);
});
$(newNestedForm).find("select,input").each(function(){
oldId = $(this).attr("id");
newId = oldId.replace(new RegExp(/_[0-9]+_/), "_" + formsOnPage + "_");
$(this).attr("id", newId);
oldName = $(this).attr("name");
newName = oldName.replace(new RegExp(/\[[0-9]+\]/), "[" + formsOnPage + "]");
$(this).attr("name", newName);
});
$(newNestedForm).insertAfter(lastNestedForm);
});
$(".duplicatable-nested-form").on("click", ".remove-duplicate-nested-form", function(event){
event.preventDefault();
$(this).parent(".duplicatable-nested-form").slideUp().remove();
});
});
它工作得很好,但只有一次。因此,当用户单击按钮添加字段时,会创建newNestedForm
并将其添加到DOM。之后,当点击该按钮时,javascript仍会生成newNestedForm
,但它未添加到DOM
。知道为什么会这样吗?或者我如何更好地调试这个?
编辑:这是我的观点的形式
<%= form_for(@gallery, html: {multipart: true}) do |f| %>
<%= f.label :pictures %><br />
<ul>
<%= f.fields_for :pictures do |p| %>
<li class="clearfix duplicatable-nested-form">
<% if p.object.image.length > 1 %>
<%= image_tag(p.object.image) %>
<% end %>
<%= p.file_field :image %>
<%= p.text_field :title %>
<% if p.object.new_record? %>
<br />
<%= link_to "Remove", "", remote: true, class: "remove-duplicate-nested-form" %>
<% else %>
<%= link_to "Remove", gallery_picture_path(@gallery, p.object), method: :delete, remote: true, class: "remove-duplicate-nested-form" %>
<%= p.hidden_field :id %>
<% end %>
</li>
<% end %>
</ul>
<%= link_to "Add another picture", "", class: "duplicate-nested-form"%>