2010-11-02 32 views
1

這似乎相對簡單,我只是難住jQuery語法。在jQuery中克隆表單並增加索引

基本上我想採取這種形式:

<div class="me_signup"> 
    <input type="text" name="referral[0][name]" id="referral_0_name"> 
    <br> 
    <input type="text" name="referral[0][email]" id="referral_0_email"> 
</div> 

並配有按鈕複製它並增加可變數目..

$(".add_another_button").click(function(){ 
    ... 
}; 

回答

5

喜歡的東西this

$(".add_another_button").click(function() { 
    var $newdiv = $(".me_signup:last").clone(true); 
    $newdiv.find('input').each(function() { 
     var $this = $(this); 
     $this.attr('id', $this.attr('id').replace(/_(\d+)_/, function($0, $1) { 
      return '_' + (+$1 + 1) + '_'; 
     })); 
     $this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) { 
      return '[' + (+$1 + 1) + ']'; 
     })); 
     $this.val(''); 
    }); 
    $newdiv.insertAfter('.me_signup:last'); 
}); 
+0

您是GENIUS STATUS。你的黃金版本在哪裏,以便我可以做出適當的頂禮? – Trip 2010-11-02 15:48:36

+0

我知道我已經檢查了這個,但我仍然被吹走。我不能夠感謝你。你對正則表達式的理解令人驚訝。 – Trip 2010-11-02 15:55:11

0

您可以將所有的html放入一個變量中,並使用.append()方法將其添加到特定的DOM元素。而且,你應該克隆這個,確保將「id」改爲「class」,因爲id在每個頁面上必須是唯一的。 Some more about .append() in official documentation