2012-04-13 53 views
0

我的演示,真的很清楚,當我克隆我的元素 克隆和刪除div但是,最後一個元素(李)不應該被刪除。 我錯過了什麼?jQuery的克隆功能嵌套刪除選項

要做些什麼與此!:

$(document).on("click", 'li.delete',function() { 
      $(this).closest(".outerDiv").remove(); 
    if ($(this).is(".outerDiv:last")){ 
      return false; 
    } 

DEMO: http://jsfiddle.net/XeELs/86/

JQUERY VAR cloneCount = 0; 。 $( 「#附加地址」)點擊(函數(){

$("#to-add-address").clone() 
     .attr("id", "to-add-address_Clone" + cloneCount) 
     .insertAfter("#to-add-address"); 
    $("#clone", "#to-add-address_Clone" + cloneCount) 
     .attr("id", "clone_Clone" + cloneCount); 
    cloneCount++; 
}); 

$(document).on("click", '.options li a',function() { 
      $(this).closest(".options").find('li a').removeClass('selected'); 
      $(this).addClass('selected'); 

     }); 
$(document).on("click", 'li.delete',function() { 
      $(this).closest(".outerDiv").remove(); 
    if ($(this).is(".outerDiv:last")){ 
      return false; 
    } 

});

回答

1

試試這個代碼

var cloneCount = 0; 
$("#add-address").click(function() { 

    $("#to-add-address").clone() 
     .attr("id", "to-add-address_Clone" + cloneCount) 
     .insertAfter("#to-add-address").addClass('cloned'); //add a new class cloned to the cloned outerDivs 
    $("#clone", "#to-add-address_Clone" + cloneCount) 
     .attr("id", "clone_Clone" + cloneCount); 
    cloneCount++; 
}); 

$(document).on("click", '.options li a',function() { 
      $(this).closest(".options").find('li a').removeClass('selected'); 
      $(this).addClass('selected'); 

     }); 
$(document).on("click", 'li.delete',function() { 
      $(this).closest(".outerDiv").filter('.cloned').remove(); // and delete only the cloned ones 
    if ($(this).is(".outerDiv:last")){ 
      return false; 
    } 
}); 
1

使用size()方法來找出有多少地址塊有,這會讓你刪除,直到只有一個左:

$(document).on("click", 'li.delete',function() { 

    if ($('.outerDiv').size() > 1){ 
      $(this).closest(".outerDiv").remove(); 
    } 

} 

http://jsfiddle.net/2mby5/