用于在jQuery中重新排列html表的代码

问题描述 投票:0回答:1

我怎么能这样做:

<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列,但可以是任意数量)更改列数。我怎么能实现这个目标?

jquery html-table
1个回答
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/

我希望,这就是你要找的东西。如果您需要有关代码的更多信息,请告诉我们!

© www.soinside.com 2019 - 2024. All rights reserved.