2012-01-12 118 views
1

試圖讓我的1錶行自動克隆24次,然後得到「添加行+」按鈕來克隆附加。JQuery循環克隆

例子可以在這裏找到:http://jsfiddle.net/CzZxf/17/

var uniqueIds = $("#math-table tr").length; 
$("#button").click(function(){ 
var $thisRow = $(this).closest("tr"), 
$clone = $thisRow.removeClass().clone(),    // Clone row 
$inputs = $clone.find("input").val("").removeClass(); 
uniqueIds++; //Increment ID 
$inputs[0].id = "A" + uniqueIds; 
$inputs[1].id = "B" + uniqueIds; 
$inputs[2].id = "C" + uniqueIds; 


$thisRow.after($clone);      
}); 
+0

你有沒有看着http://stackoverflow.com/questions/171027/add-table-row-in-jquery – j08691 2012-01-12 22:11:34

回答

2

你誤會.closest,它的工作方式類似於.parents

我固定橫移找到最後tr這裏:http://jsfiddle.net/CzZxf/19/

var $thisRow = $("#math-table tr:last-child")

+0

你是對的。謝謝!我將在哪裏添加循環代碼來克隆24次,每次都使用我的唯一ID? – user1040259 2012-01-12 22:16:14

+0

@ user1040259'var l = 24; (1--){(「#button」)。trigger(「click」); }'http://jsfiddle.net/CzZxf/22/ – Esailija 2012-01-12 22:17:41

+0

謝謝!現在我需要研究你做了什麼。 – user1040259 2012-01-12 22:21:18

1

我更喜歡使用比使用克隆的模板。看我的DEMO here,

下面的addRow函數會向表中添加一個新行。

var rowTmpl = '<tr>' + 
     '<td><input type="text" id="A{ID}" name="A" value=""></td>' + 
     '<td><input type="text" id="B{ID}" name="B" value=""></td>' + 
     '<td><input type="text" id="C{ID}" name="C" readonly="readonly" tabIndex="-1" value=""></td>' + 
     '</tr>'; 

function addRow() {  
    var rowCount = $('#math-table tbody tr').length; 

    //modify template 
    var addRow = rowTmpl.replace (/{ID}/g, rowCount); 

    //append to the tbody 
    $('#math-table tbody').append(addRow); 
}