我有一张这样的表,
<table class='location'>
<tbody>
<tr align=center>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
<td>Content 7</td>
<td>Content 8</td>
</tr>
</tbody>
</table>
我想使用JQuery重新安排此表,
<table class='location'>
<tbody>
<tr align=center>
<td>Content 1</td>
<td>Content 2</td>
</tr>
<tr align=center>
<td>Content 3</td>
<td>Content 4</td>
</tr>
<tr align=center>
<td>Content 5</td>
<td>Content 6</td>
</tr>
<tr align=center>
<td>Content 7</td>
<td>Content 8</td>
</tr>
</tbody>
</table>
每行2个细胞。即4行,每行2个单元。
请指导我,因为我是JQuery的初学者。
由于
答案 0 :(得分:2)
应用了以下几种jQuery方法,例如each(),append(),attr(),first()和last()。此外,旧版Stackoverflow answer中的 isOdd 函数用于检查td
元素位置。
// loop through each table td element
$("table.location td").each(function (index) {
// check if it's odd or even td element based on its position
// element index is added 1 before checking if its position has even or odd number because index starts from 0
var odd = isOdd((index + 1));
//if td element is position order number is odd then create new table row
//and append it to the table
if (odd) {
$("table.location tbody").append($("<tr>").attr("align", "center"));
}
//then append the current td element to the last table row
//the last table row is the most recently created row
$("table.location tr").last().append($(this));
});
//finally remove the first table row which is empty
$("table.location tr").first().remove();
function isOdd(num) {
return num % 2;
}
我希望你能找到答案: - )