我想转置 HTML 表中的行和列,即行作为列,列作为行。
我可以通过什么方式做到这一点?
例子 :
1 4 7
2 5 8
3 6 9
作为
1 2 3
4 5 6
7 8 9
我想转置 HTML 表中的行和列,即行作为列,列作为行。
我可以通过什么方式做到这一点?
例子 :
1 4 7
2 5 8
3 6 9
作为
1 2 3
4 5 6
7 8 9
html:
<table>
<tr>
<td>1</td>
<td>4</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>9</td>
</tr>
</table>
<p><a href="#">Do it.</a></p>
js:
$("a").click(function(){
$("table").each(function() {
var $this = $(this);
var newrows = [];
$this.find("tr").each(function(){
var i = 0;
$(this).find("td").each(function(){
i++;
if(newrows[i] === undefined) { newrows[i] = $("<tr></tr>"); }
newrows[i].append($(this));
});
});
$this.find("tr").remove();
$.each(newrows, function(){
$this.append(this);
});
});
return false;
});
David Bushell 有一个 CSS 解决方案(使用 flexbox):http ://dbushell.com/2016/03/04/css-only-responsive-tables/
还有这个 CSS 解决方案(使用浮动)
tr { display: block; float: left; }
th, td { display: block; }
(在这个答案中都提到了它们:HTML Table with vertical rows)
这应该适用于任意 html:
function swap( cells, x, y ){
if( x != y ){
var $cell1 = cells[y][x];
var $cell2 = cells[x][y];
$cell1.replaceWith( $cell2.clone() );
$cell2.replaceWith( $cell1.clone() );
}
}
var cells = [];
$('table').find('tr').each(function(){
var row = [];
$(this).find('td').each(function(){
row.push( $(this) );
});
cells.push( row );
});
for( var y = 0; y <= cells.length/2; y++ ){
for( var x = 0; x < cells[y].length; x++ ){
swap( cells, x, y );
}
}
工作小提琴:
你想用什么语言来做?我假设 JavaScript,正如你所说的 jQuery。(jQuery 不是一种语言,它是一种语言的库)
您需要找到一种将表表示为数据结构的方法。为简单起见,这应该通过 OOP 完成。我建议您获取列数和行数,并将数据放入 1 个单一的平面数组中。
您还需要设计一些可以解析 HTML 并获取表格的内容,将其转换为您的结构,从而轻松完成计算。这可以通过 jQuery 的方法来完成。
然后你需要找到一个排序函数来对平面数组进行排序。
最后,您需要将数组分解为适当的列和行并重新呈现 HTML。
看!没那么难。设计已经为您完成了,您所需要的只是实现它。(也许我不应该为你做那么多工作..)
我正在寻找一种非 jquery 的方式来做这件事并想出了这个:
const transposeTable = (tbody, newContainerType = "tbody") => {
const rows = Array.from(tbody.querySelectorAll("tr"))
const newTbody = document.createElement(newContainerType)
for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
const row = rows[rowIdx]
const cells = Array.from(row.querySelectorAll("td, th"))
for (let cellIdx = 0; cellIdx < cells.length; cellIdx++ ) {
const cell = cells[cellIdx]
const newRow = newTbody.children[cellIdx] || document.createElement("tr")
if (!newTbody.children[cellIdx]) {
newTbody.appendChild(newRow)
}
newRow.appendChild(cell.cloneNode(true))
}
}
// Do live DOM manipulations only once for performance
tbody.parentElement.appendChild(newTbody)
tbody.parentElement.removeChild(tbody)
}
transposeTable(document.querySelector("tbody"))