这里有一些代码可以“翻转”一张桌子
th
的定义。
-
它计算出有多少行;
-
它设置了一些模板
-
然后,它会遍历标题并读取将其转录到行的列。
-
将该行添加到新表中。
-
把旧桌子换成新桌子。
注意
旧桌子上的任何处理程序都会消失,因为桌子上没有
第
s代码无法将其切换回。这只是一个起点。
$("button.flip").click(function(e) {
e.preventDefault();
var $table = $(this).prev("table");
var $newTable = $("<table>");
var $newRowTemplate = $("<tr>");
var rowCount = $table.find("tr").length;
for (let i = 1; i <= rowCount; i++) {
$newRowTemplate.append("<td>");
}
$.each($table.find("tr:first-child > th"), function(col, cell) {
var $newRow = $newRowTemplate.clone();
var txt = "";
$($newRow.find("td")[0]).html($(cell).text());
for (let y = 1; y <= rowCount; y++) {
txt = $table
.find(`tr:nth-child(${y}) > td:nth-child(${col+1})`).text();
$($newRow.find("td")[y]).html(txt);
}
$newTable.append($newRow);
});
//$(this).after($newTable);
if (!$newTable.is(":empty")) {
$table.remove();
$(this).before($newTable);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Student</th>
<th>Class</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>History</td>
<td>B</td>
</tr>
<tr>
<td>Sarah</td>
<td>English</td>
<td>D</td>
</tr>
<tr>
<td>Sam</td>
<td>Math</td>
<td>A</td>
</tr>
</tbody>
</table>
<button class="flip">flip</button>
编辑
经过一点努力,我能够使这个工作,然后反向本身,我再次怀疑任何事件处理程序将丢失。
$("button.flip").click(function(e) {
e.preventDefault();
var $table = $(this).prev("table"); //orig table reference
var $newTable = $("<table>"); //new table placeholder
var rowCount = $table.find("tr").length; //the number of rows in the orig table
//loop through the first rows cells
$.each($($table.find("tr")[0]).children(), function(col, cell) {
var $newRow = $("<tr>"); //create a new row
$newRow.append($(cell).clone()); //append the current cell
//traverse the column appending the cells to the row as we go
for (let y = 1; y <= rowCount; y++) {
$newRow.append($($($table.find("tr")[y]).children()[col]).clone());
}
$newTable.append($newRow); //put the new row in the new table
});
//if I managed to do some work lets remove the old table and replace it with the new one
if (!$newTable.is(":empty")) {
$table.remove();
$(this).before($newTable);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Student</th>
<th>Class</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>History</td>
<td>B</td>
</tr>
<tr>
<td>Sarah</td>
<td>English</td>
<td>D</td>
</tr>
<tr>
<td>Sam</td>
<td>Math</td>
<td>A</td>
</tr>
<tr>
<td>Quinn</td>
<td>Javascript</td>
<td>D-</td>
</tr>
</tbody>
</table>
<button class="flip">flip</button>