2016-06-08 45 views
2

我在左邊有一個大按鈕,右邊有一個表格。當你點擊左邊的按鈕時,它允許你總共創建6個表格。這是設定的限制,你不能超過它。我點擊創建div的克隆。限制是6個克隆。如果我刪除了一個克隆,它會打破限制它的代碼?

問題#1 - 如果您選擇X圖標刪除其中一個克隆。然後再開始添加更多克隆。它打破了設置的克隆限制1-6,並允許您創建無限的克隆。

問題#2 - 如何從第一個/初始形式中刪除X圖標,並且只允許其克隆上的「允許」。

謝謝!

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

回答

2

的問題是與你爲.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


UPDATE - 1

對於問題 - 2只需添加下面CSS

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

UPDATED FIDDLE 2

+0

出色的作品!你有沒有解決我的問題#2的問題?如果你沒有創建任何額外的克隆,並且你在最初的表單上點擊X,它會刪除它,然後你無法刷新就無法恢復。想知道如何隱藏它的味道配置文件#1 謝謝! – Patrick

+0

隨時..快樂編碼.. :) –

+1

順便說一句你更新的提琴2鏈接是錯誤的,但代碼段完美工作 – Patrick