2013-02-10 47 views
0

我怎麼會從這個去:jQuery代碼重新安排表

<tr> 
    <td>A</td> 
    <td><input for A></td> 
</tr> 
<tr> 
    <td>B</td> 
    <td><input for B></td> 
</tr> 

這樣:

<tr> 
    <td>A</td> 
    <td>B</td> 
</tr> 
<tr> 
    <td><input for A></td> 
    <td><input for B></td> 
</tr> 

我需要根據行數將行移入N(這個變化從數據集中檢索,在這種情況下爲2列,但可以是任意數量)的列數。我怎麼能做到這一點?

回答

1

您可以在表格數據中讀入二維數組,然後用轉置的矩陣覆蓋表格數據。

function reArrange() { 
    var table = $('table#theTable'); 
    // we will store all the table-data in a two-dim array: 
    var data = new Array(); 
    // find all rows (row-index: i): 
    $(table).find('tr').each(function(i, row) { 
     // find all cells in this row (col-index: j): 
     $(row).find('td').each(function(j, cell) { 
      // make sure, we got the array right: 
      if (data[j] === undefined) { 
       data[j] = new Array(); 
      } 
      // use col-index as first index in the array: 
      data[j][i] = $(cell).html(); 
     }); 
    }); 
    // reset table: 
    $(table).find('tr').remove(); 
    // re-fill table 
    $(data).each(function(i, elem){ 
     var row = $('<tr/>'); 
     $(elem).each(function(j, col) { 
      cell = $('<td/>').html(col); 
      $(row).append(cell); 
     }); 
     $(table).append(row); 
    }); 

} 
reArrange(); 

看一看這個的jsfiddle:http://jsfiddle.net/66YpC/2/

我希望,這就是你要找的人。如果您需要更多關於代碼的信息,請告訴我!

+0

這移動到3列,但如果我需要它在2列? – user2036094 2013-02-10 19:33:41

+0

應該適用於任意數量的列和行。試一試。只需修改jsFiddle中的HTML標記,然後單擊運行。 – ditscheri 2013-02-12 08:37:19