2012-09-24 27 views
0

我想通過運行一個循環,如下面的代碼來創建幾行:增量表行ID對循環計數器

<table> 
    <% for (var i = 0; i <= 2; i++) 
     { %> 
     <tr id="Row" +"i"> // i want to give unique row ID based on my "i" variable 
     <td><%:Html.TextBoxFor(m=>m.ChildData[i].ChildName) %></td> 
     </tr> 
     <%} %> 
</table> 

在生成的表,我想每一行都有一個唯一的ID:

<tr id="Row1">,<tr id="Row2">,<tr id="Row3">, etc. 

我該怎麼做?

回答

1
<table> 
    <% for (var i = 0; i <= 2; i++) { %> 
     <tr id="Row<%= i %>"> 
      <td> 
       <%= Html.TextBoxFor(m => m.ChildData[i].ChildName) %> 
      </td> 
     </tr> 
    <% } %> 
</table> 

但是,如果你需要這些ID來操縱JavaScript的行,那麼你真的不需要指定任何ID。例如,jQuery爲您提供了允許您傳遞選擇器當前索引的函數。例如:

$('table tr').each(function(index, row) { 
    // build the id, the same way as if you were building it on the server 
    var id = 'Row' + (index + 1); 

    // get the corresponding textbox that's inside this row 
    var textbox = $('input[type="text"]', row); 

    ... 
}); 
+0

+1擊敗我...... – nbrooks