单击带有删除按钮的克隆 div - 但是如何隐藏初始克隆上的删除按钮?

Cloning divs on click with a remove button - But how do i hide the remove button on the initial clone?

所以我左边有一个大按钮,右边有一个表单。当您单击该按钮时,它最多会创建 5 个附加表单。它还会更新 id 和风味配置文件 # text.

它仍然存在一些问题,正在寻求一些帮助来解决它,因为我不是 JS 的最佳人选。

问题 1: 如果您创建了 5 个额外的克隆然后删除它们。当您再次创建它们时,它会将它们标记为 #7 #8 #9 - 因为 只允许使用 6 种形式。 我需要这个数字 只显示 1-6 而不是高于或低于。 我也想要同样的 ID。

问题 2: 我遇到的另一个问题是我想从 中删除 "Remove button" Flavor Profile #1(第一种形式)。因为如果所有的表格都被删除,就没有什么可以克隆的了。

感谢您的帮助!

JS FIDDLE

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

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

    var new_clone =  $(".clonedInput").first().clone();

    new_clone.attr("id", "clonedInput" +  cloneIndex);
    new_clone.find(".label-nbr").text(cloneIndex);
    new_clone.find(".category").attr("id","category"+cloneIndex);
    new_clone.show(".remove").attr("id","remove"+cloneIndex);
    new_clone.on('click', 'button.clone', clone);
    new_clone.on('click', 'button.remove', remove);

    $("#formy").append(new_clone);
  }
}
function remove(){
  if(cloneIndex>1){
    $(this).parents(".clonedInput").remove();
    cloned_nbr--;
  }
}
$(".clone").on("click", clone);

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

添加一个函数来检查存在的可移动 div 数量。如果大于 1,则显示删除按钮,否则不显示:

function handleRemoveButton(){
    var numItems = $('.clonedInput').length;
    if(numItems<=1){
        $(".remove").hide();
    }
    else{
        $(".remove").show();
    }
}

并调用它三次:一次在 $(document).ready(); 上,一次在 clone(){}remove() 的最后一次。

我稍微改了一下。它应该使用适当的索引并删除按钮!

function getFreeIds() {
    var used = $('.clonedInput').find('.label-nbr').map(function(i, v) {
            return parseInt(v.innerText)
        }).get();
    return allowed.filter(function (i) {return used.indexOf(i) === -1});
}

它满足您的需求。

http://jsfiddle.net/tfFLt/1921/

编写一个重新排列函数来更新内容并在克隆项目或删除项目时调用它

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++;
    });
}

检查 jsfiddle:http://jsfiddle.net/tfFLt/1922/