2012-02-02 123 views
0

嗨我有一個輸入框,需要根據.clone()函數克隆六次,我可以做到這一點,但如果輸入名稱必須改變,如何做到這一點。克隆輸入框

http://api.jquery.com/clone/

<label for="input"> 
<input name="input" id="input" type="text"> 
</label> 

<a href="#" onClick="cloneInput()">Add Another Input</a> 

所以我們可以說,當一個新的輸入創建它應該添加一個增量的名稱和編號,即:name="input2"id="input2"等,每次對象被克隆。

任何人有任何建議,最好/最簡單的方法來做到這一點與jQuery?

+0

哪裏是'cloneInput'的代碼? – 2012-02-02 14:57:02

回答

2

首先刪除內嵌事件處理使用jQuery和而不是使用clone你可以試試這個。

標記

<div id="inputContianer"> 
    <label for="input"> 
    <input name="input" id="input" type="text"> 
    </label> 
</div> 

<a class="cloneInput" href="#">Add Another Input</a> 

JS

$(function(){ 
    var count = 1; 
    $('a.cloneInput').click(function(){ 
     var id = 'input' + (count++); 
     $('<label />', { for: id }) 
     .append($('<input />', { id: id, name: id, type: "text" })) 
     .appendTo('#inputContianer'); 

     return false; 
    }); 
}); 
+0

即使使用clone(),這也是正確的方法。我正在[打字](http://jsbin.com/atomid/2)在jsbin上類似的過程。 – Sorpigal 2012-02-02 15:14:28

1

在你cloneInput功能,您可以向屬性賦值到像這樣的元素:

$('input').last().attr('name', 'a_new_name'); 

這個例子會發現你的最後一個輸入字段中指定一個新的名稱。爲ID的同一作品,價值觀等等看它:http://api.jquery.com/attr/

或者像詹姆斯指出的那樣,克隆後直接運行()太:

$('#clone_me').clone().attr('id', 'im_the_clone'); 
+0

您不需要使用'last',只需將它與'.clone()'一起鏈接即可,無需在已經引用DOM時搜索DOM。 – 2012-02-02 14:58:04

0

好像這個工作:

<script> 
    var c = 1; 
    function cloneInput() { 
     $('#input') 
       .clone() 
       .attr('id', 'input'+c) 
       .attr('name', 'input'+c) 
       .appendTo('#clones') 
       .wrap('<label for="input'+c+'"/>'); 
     c++; 
    } 
</script> 

<label for="input"> 
<input name="input" id="input" type="text"> 
</label> 

<a href="#" onClick="cloneInput()">Add Another Input</a> 

<div id="clones"></div>