2012-04-13 50 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/