试试这个http://jsfiddle.net/w2n7B/5/
示例用法:
var table = document.getElementById('table');
var tbl = new jTable(2);
var rTable = tbl.transformTable(table));
document.getElementById('popup').appendChild(rTable);
注意: th 必须出现在源表中
HTML
<table id="tbl">
<tr>
<th>h1</th>
<th>h2</th>
<th>h3</th>
</tr>
<tr>
<td>1 - 1</td>
<td>1 - 2</td>
<td>1 - 3</td>
</tr>
<tr>
<td>2 - 1</td>
<td>2 - 2</td>
<td>2 - 3</td>
</tr>
<tr>
<td>3 - 1</td>
<td>3 - 2</td>
<td>3 - 3</td>
</tr>
<tr>
<td>4 - 1</td>
<td>4 - 2</td>
<td>4 - 3</td>
</tr>
<tr>
<td>5 - 1</td>
<td>5 - 2</td>
<td>5 - 3</td>
</tr>
</table>
<div id="copy"></div>
Javascript
function jTable(maxRows, withHeaders){
var _maxRows = 0;
var _withHeaders = false;
//maxRows - max rows
//withHeaders - with header on each column
var construct = function(maxRows, withHeaders){
_maxRows = maxRows;
_withHeaders = typeof(withHeaders) == 'undefined' ? false : withHeaders;
}
//sourceTable - table with data to be converted into limited number of rows table
this.transformTable = function(sourceTable){
//create limited rows table(rTable)
var copyTable = document.createElement('table');
//store source table headers
var headers = sourceTable.rows[0].cells;
for(var r = 0; r < sourceTable.rows.length - 1; r++){
//defined index of rTable row
var index = r - Math.floor(r / _maxRows) * _maxRows;
var row = copyTable.rows[index] || copyTable.insertRow(index);
//copy cells
for(var c = 0; c < headers.length; c++){
var cell = row.insertCell(row.cells.length);
cell.innerText = sourceTable.rows[r + 1].cells[c].innerText;
}
}
addHeaders(copyTable, sourceTable.rows[0].cells);
return copyTable;
}
//add headers to rTable
var addHeaders = function(table, headers){
var headerRow = table.insertRow(0);
var headerCount = _withHeaders ? table.rows[1].cells.length : headers.length;
for(var h = 0; h < headerCount; h++){
var th = document.createElement('th');
//index of source table header
var textIndex = h - Math.floor(h / headers.length) * headers.length;
th.innerText = headers[textIndex].innerText;
headerRow.appendChild(th);
}
}
construct.call(this, maxRows, withHeaders)
}
window.onload = function(){
var sourceTable = document.getElementById('tbl');
var tTable = new jTable(2, false);
document.getElementById('copy').appendChild(tTable.transformTable(sourceTable));
}