我在单击时创建了 div 的克隆。限制是 6 个克隆。如果我删除一个克隆,它会破坏限制它的代码吗?

I create a clone of a div on click. The limit is 6 clones. If I delete a clone it breaks the code that limits it?

我左边有一个大按钮,右边有一个表单。当您单击左侧的按钮时,您总共可以创建 6 个表单。那是设定的限制,你不能超过它。

问题 #1 - 如果您 select X 图标删除其中一个克隆。然后再次开始添加更多克隆。它打破了 1-6 的克隆限制并允许您创建无限克隆。

问题 #2 - 我如何从 first/initial 表单中删除 X 图标并仅在其克隆上 "allowed"。

谢谢!

JS FIDDLE

JS

var clones_limit = 5;
var cloned_nbr = $(".clonedInput").length-1; //Exclude Default (first) div 

function clone()
{
  if(cloned_nbr<clones_limit)
  {
    cloned_nbr++;

    var new_clone =  $(".clonedInput").first().clone();
    $("#formy").append(new_clone);
    rearrange();
  }
}
function remove(){
    $(this).parents(".clonedInput").remove();
    cloned_nbr--;
   rearrange();
}

function rearrange(){
var count = 1;
var totalCount = $(".clonedInput").length;
$(".clonedInput").each(function(){
$(this).attr("id", "clonedInput"+count).find(".label-nbr").text(count).end().
find(".category").attr("id","category"+count).end().find(".remove").toggle(totalCount!=1).attr("id","remove"+count).on("click", remove);
count++;
});
}
$(".clone").on("click", clone);

$(".remove").on("click", remove);

问题在于您为 .remove 元素附加 click event 的方式。由于您在创建时附加了它,它过去常常为所有重新创建的元素触发 remove,因此将 cloned_nbr 的计数减少回 0。所以只需删除 click 事件附加并使用 event delegation

错误代码

function rearrange() {
  var count = 1;
  var totalCount = $(".clonedInput").length;
  $(".clonedInput").each(function() {
    $(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
    .find(".category").attr("id", "category" + count).end().find(".remove")
    .toggle(totalCount != 1).attr("id", "remove" + count).on("click", remove);
                                                       //^^^this was causing the issue
    count++;
  });
}

下面是你需要做的修改。

更新代码

function rearrange() {
  var count = 1;
  var totalCount = $(".clonedInput").length;
  $(".clonedInput").each(function() {
    $(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
    .find(".category").attr("id", "category" + count).end().find(".remove")
    .toggle(totalCount != 1).attr("id", "remove" + count);
                                                          //^^^No need to attach here
    count++;
  });
}

$(document).on("click", ".remove", remove);//Event delegation

UPDATED FIDDLE HERE


更新 - 1

对于问题- 2只需在下面添加CSS

div[id^="clonedInput"]:first-child .remove{
  display:none;
}

UPDATED FIDDLE 2