2013-03-22 71 views
0

我正在使用此代碼進行克隆。如何在jquery中克隆

  1. 我要修改這個代碼,當我點擊克隆按鈕,它一次又一次克隆克隆刪除按鈕,每一個新生成的動態格。

  2. 當我在克隆按鈕,單擊它第一次用相同的ID ID = clonedInput1,之後,它開始增量克隆同一div。

您可以在這裏找到一個工作版本http://jsfiddle.net/shalucosmic/FEpMk/7/

<script type="text/javascript"> 
    $(document).ready(function(){ 
     //jQuery(this).parent(".clonedInput") 
      var regex = /^(.*)(\d)+$/i; 
      var cloneIndex = $(".clonedInput").length; 

      $("button.clone").live("click", function(){ 

      $(this).parents(".clonedInput").clone().appendTo("body").attr("id", "clonedInput" + cloneIndex) 
      .find("*").each(function() { 
      var id = this.id || ""; 
      var name = this.name || ""; 

      var match = id.match(regex) || []; 

      var matchname = name.match(regex) || []; 
      if (match.length == 3) { 
      this.id = match[1] + (cloneIndex); 
      } 
      if (matchname.length == 3) { 
      this.name = match[1] + (cloneIndex); 
      } 
}); 
cloneIndex++; 

}); 
$("button.remove").live("click", function(){ 
    $(this).parents(".clonedInput").remove(); 
}); 

}); 

<div id="clonedInput1" class="clonedInput"> 
    <input type="text" name="contributer1" value="" id="contributer1"/> 

    <div class="actions"> 
    <button class="clone">Clone</button> 
    <button class="remove">Remove</button> 
    </div> 
</div> 
+0

謝謝回覆你們,但我想克隆和刪除按鈕只有一次並不總是。它的身體上的每一件事我都需要追加下一個。 – Chauhan 2013-03-22 10:55:23

回答

1

需要在克隆輸入長度增加1

var cloneIndex = $(".clonedInput").length + 1; 
            // -----^^^^ here 

fiddle here

1

在聲明cloneIndex時,您需要聲明如下。

var cloneIndex = $(".clonedInput").length+1; 

DEMO

2

可以簡化爲

$(document).ready(function() { 
    // jQuery(this).parent(".clonedInput") 
    var regex = /^(.*)(\d)+$/i; 
    var cloneIndex = $(".clonedInput").length + 1; 

    $(document).on("click", 'button.clone', function() { 
     $(this).closest(".clonedInput").clone().appendTo("body").attr("id", 
       "clonedInput" + cloneIndex).find("[id], [name]").each(
       function() { 
        this.id = this.id.replace(/\d+$/, cloneIndex); 
        this.name = this.name.replace(/\d+$/, cloneIndex); 
       }); 
     cloneIndex++; 
    }); 

    $("button.remove").live("click", function() { 
       $(this).parents(".clonedInput").remove(); 
      }); 

}); 

演示:Fiddle