我有下面的HTML表。
<table id="table">
<tbody>
<tr>
<th>City</th>
</tr>
<tr>
<td>Madrid</td>
</tr>
<tr class="show-on-top">
<td data-order="3">London</td>
</tr>
<tr>
<td>Berlin</td>
</tr>
<tr>
<td data-order="1">Paris</td>
</tr>
<tr class="show-on-top">
<td data-order="2">Rome</td>
</tr>
</tbody>伦敦、巴黎和罗马有一个名为show-on-top的班级。顾名思义,我希望将所有的tr都移动到show-on-top表的顶部。我可以用下面的代码来完成这个任务。
$("#table tbody").prepend($('.show-on-top'));但问题是,伦敦、巴黎和罗马出现在<th> (“城市”标题)前面。当然,我希望将show-on-top行放在表的顶部,但放在标题(第一行)之后。所以我想出了以下的想法。
$("#table tbody tr:eq(1)").prepend($('.show-on-top'));我就快到了。我的所有show-on-top都放在标题之后,但它们嵌套在tr中,如下所示。
<table id="table">
<tbody>
<tr>
<th>City</th>
</tr>
<tr>
<tr class="show-on-top">
<td data-order="3">London</td>
</tr>
<tr>
<td data-order="1">Paris</td>
</tr>
<tr class="show-on-top">
<td data-order="2">Rome</td>
</tr>
</tr>
<tr>
<td>Madrid</td>
</tr>
<tr>
<td>Berlin</td>
</tr>
</tbody>我不明白我的所有行是如何嵌套在tr中的。我尝试了数百种parent,after,prepend,append的组合,但都没有成功。
奖金问题。show-on-top行具有data-order属性,表示我希望对所讨论的第四行进行排序的顺序(巴黎>罗马>伦敦)。我用了sort.data('order'),但什么也没发生。我甚至不能在console.log()上看到任何东西。
谢谢您抽时间见我。
发布于 2020-07-10 23:51:20
您可以使用insertAfter()和:first选择器。
$(".show-on-top").insertAfter('#table tbody tr:first');.show-on-top{ color:red}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tbody>
<tr>
<th>City</th>
</tr>
<tr>
<td>Madrid</td>
</tr>
<tr class="show-on-top">
<td data-order="3">London</td>
</tr>
<tr>
<td>Berlin</td>
</tr>
<tr>
<td data-order="1">Paris</td>
</tr>
<tr class="show-on-top">
<td data-order="2">Rome</td>
</tr>
</tbody>
</table>
发布于 2020-07-10 22:57:03
您可以做的一件事是将标题行从<tbody>移到<thead>中。
$("#table tbody").prepend($('.show-on-top'));<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Madrid</td>
</tr>
<tr class="show-on-top">
<td data-order="3">London</td>
</tr>
<tr>
<td>Berlin</td>
</tr>
<tr>
<td data-order="1">Paris</td>
</tr>
<tr class="show-on-top">
<td data-order="2">Rome</td>
</tr>
</tbody>
</table>
另一种解决方案是使用.after()将行放在包含th的最后一行之后。
$("#table tbody tr:has(th):last").after($(".show-on-top"));<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tbody>
<tr>
<th>City</th>
</tr>
<tr>
<td>Madrid</td>
</tr>
<tr class="show-on-top">
<td data-order="3">London</td>
</tr>
<tr>
<td>Berlin</td>
</tr>
<tr>
<td data-order="1">Paris</td>
</tr>
<tr class="show-on-top">
<td data-order="2">Rome</td>
</tr>
</tbody>
</table>
https://stackoverflow.com/questions/62843357
复制相似问题