2012-07-10 78 views
0

我有這個問題使用jQuery的.each()函數。 我想排序我有一個表的行和列,我試圖通過向我的'td'標記添加名爲'row'和'col'的屬性來完成。jQuery .each()函數問題

基本上是我的代碼如下所示:

$('tr').each(function(tr_index) { 
    $('td').each(function(td_index) { 
     $(this).attr({ 
      'row' : tr_index, 
      'col' : td_index, 
     }); 
    }); 
}); 

,但是這給了我下面的輸出:

<td row="6" col="0"></td> 
<td row="6" col="1"></td> 
<td row="6" col="2"></td> 
<td row="6" col="3"></td> 
<td row="6" col="4"></td> 
<td row="6" col="5"></td> 
<td row="6" col="6"></td> 

行對每一個 'TD' 標籤屬性的輸出6。這是否意味着第一個.each()循環在任何第二個.each()循環被觸發之前執行?

任何想法如何我可以改變這一點,使我有這樣的事情:

<td row="0" col="0"></td> 
<td row="0" col="1"></td> 
<td row="0" col="2"></td> 
<td row="1" col="0"></td> 
<td row="1" col="1"></td> 
<td row="1" col="2"></td> 
<td row="2" col="0"></td> 

等等

我將不勝感激,如果任何人有一個解決這個問題對我來說,因爲我似乎無法繞過它。

+0

看起來你有你的解決方案,但它會更好地使用[HTML5數據屬性(http://html5doctor.com/html5-custom-data-attributes/),而比僞造屬性。 – steveax 2012-07-10 01:03:18

回答

5

試試這個

 $('tr').each(function(idx_row){ 
      $(this).children().each(function(idx_col){ 
       $(this).attr({'row':idx_row, 'col':idx_col}); 
      }) 
     }); 
+0

謝謝!那完美的工作。我以爲我已經嘗試過了,但我一定犯了錯誤。 – 2012-07-10 00:43:12