2010-04-30 32 views
0

我有一个表,看起来像这样:所以,我有这个jQuery位,增加了一个行到表我需要它的方式,但它的丑陋

<table name="exercises" id="workout-table"> 
<tr> 
<th>Name</th> 
<th>Reps/Intervals</th> 
<th>Sets</th> 
<th>Weight/Distance/Time</th> 
</tr> 


[%- i=0 %] 
[% WHILE i<=10 %] 
<tr class="workout-rows"> 
<td><input type="text" name="workout[exercise][[% i %]][name]" /></td> 
<td><input type="text" name="workout[exercise][[% i %]][repetitions]" size="3"/></td> 
<td><input type="text" name="workout[exercise][[% i %]][sets]" size="3"/></td> 
<td><input type="text" name="workout[exercise][[% i %]][weight]" size="4"/></td> 
</tr> 
[% i = i + 1 %] 
[% END %] 

</table> 

该模板的代码模板::工具箱代码基本上只是生成一个索引,所以我可以跟踪从Catalyst :: Plugin :: Params :: Nested将成为HoAoH的元素。这是实际上增加了该行的表上按一下按钮的JavaScript:

$("#add-row").click(function(){ 
     var size = $(".workout-rows").length; 
     //size += 1; 
     var row ='<tr class="workout-rows">' + 
     '<td><input type="text" name="workout[exercise][' + size + '][name]" /></td>' + 
     '<td><input type="text" name="workout[exercise][' + size + '][repetitions]" size="3"/></td>' + 
     '<td><input type="text" name="workout[exercise][' + size + '][sets]" size="3"/></td>' + 
     '<td><input type="text" name="workout[exercise][' + size + '][weight]" size="4"/></td>' + 
     '</tr>'; 

     $("#workout-table >tbody tr:last").after(row) 
    }); 

我真的真的不喜欢复制粘贴的想法表行标记到脚本本身,因为它是重复的和非,直观。我已经尝试过.clone的东西,它非常适合逐字复制行,但它并不像我需要的那样动态跟踪行数。

所以基本上我已经削减到需要找出如何混淆每个输入的名称,以便它可以反映适当的循环索引,所以Catalyst :: Plugin :: Params :: Nested将构建正确的结构。

想法?

回答

4

您应该创建一个返回表克隆的函数。我一直使用这个模板:

<div id="tableTemplate" style="display: none;"> 
    <table> 
     <tr class="workout-rows"> 
     <td> <input type="text" name="" /> </td> 
     <td> <input type="text" name="" size="3" /> </td> 
     <td> <input type="text" name="" size="3" /> </td> 
     <td> <input type="text" name="" size="4" /> </td> 
     </tr> 
    </table> 
</div> 

然后,你克隆那个模板。

function createTableRow(size) 
{ 
    var template = $('#tableTemplate').clone(true); 
    template = template.find('tr'); // Dont need to clone the table tag 
    template.find('td:nth-child(1)').find('input').attr('name', 'workout[exercise][' + size + '][name]'); 

    // Similar logic for the other names 

    return template; 
} 
相关问题