2012-05-29 46 views
1

我有HTML這樣的:如何使用不同名稱的jquery克隆生成HTML?

<div id='main'> 

    <div id='child-0'> 
    <input type='text' name='data[0][name]'> 
    <input type='text' name='data[0][dob]'> 
    <input type='text' name='data[0][location]'> 
    </div> 

</div> 

<input type='button' id='add' value='Add'> 

的jQuery:

$("input#add").live('click', function(){ 
    $("#main").append("<br />"); 
    $("#child-0").clone(false).appendTo($("#main")); 
}); 

Above code is working but it is creating elements with same name。我想生成這樣的東西:

<div id='main'> 

    <div id='child-0'> 
    <input type='text' name='data[0][name]'> 
    <input type='text' name='data[0][dob]'> 
    <input type='text' name='data[0][location]'> 
    </div> 

    <div id='child-1'> 
    <input type='text' name='data[1][name]'> 
    <input type='text' name='data[1][dob]'> 
    <input type='text' name='data[1][location]'> 
    </div> 

</div> 

什麼是簡單的解決方案。

感謝

+2

誤導性的標題? – dotjoe

+0

其中是'? – undefined

+1

對不起,誤導性的標題。 Stackoverflow現在保存您最近的編輯,我忘了更改。 – Student

回答

2
$("input#add").live('click', function(){ 
    $("#main").append("<br />"); 
    var cloned = $("#main div:last").clone(false).appendTo($("#main")); 
    cloned.find('[name^=data]').attr('name', function() { 
     var index = this.name.match(/\[(\d)\]/); 
     if (index != null && index.length > 1) { 
      var newIndex = parseInt(index[1], 10) + 1; 
      return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']'); 
     } 
     return this.name;  
    }); 
});​ 
+0

感謝您的回覆,但它正在創建數組索引1('data [1] [name]')的所有新元素:http://jsfiddle.net/4u6qD/4/ – Student

+1

對不起,我在選擇器中犯了一個錯誤。我現在已經更新了答案:http://jsfiddle.net/NLaJA/ –

相關問題