我有一些带有这些 html 结构的动态生成的表
<table class="deliver">
<tbody class="tbody">
<tr id="10" data-position="10">
<td>Title</td>
</tr>
<tr id="10" data-position="10">
<td>Content</td>
</tr>
<tr id="23" data-position="23">
<td>Title</td>
</tr>
<tr id="23" data-position="23">
<td>Content</td>
</tr>
</tbody>
</table>
<table class="deliver">
<tbody class="tbody">
<tr id="3" data-position="3">
<td>Title</td>
</tr>
<tr id="3" data-position="3">
<td>Content</td>
</tr>
<tr id="2" data-position="2">
<td>Title</td>
</tr>
<tr id="2" data-position="2">
<td>Content</td>
</tr>
<tr id="2" data-position="2">
<td>Extra content (sometimes)</td>
</tr>
</tbody>
</table>
每个表都有一个tbody和tr。 id 和数据位置范围在 1 到 23 之间。我需要某种排序方法来保留标题内容对,但在每个表中对 id 进行升序排序。我发现this和 this教程,但在我的情况下不起作用(什么也没有发生)。
我的代码片段如下所示
$(".tbody").each(function(){
$(this).html($(this).children('tr').sort(function(a, b){
return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
}));
});
最佳答案
您可以使用 Array.prototype.sort用于非平凡排序的回调。
下面的演示循环遍历所有表并排序 <tr>
s 同时尊重 data-position
属性升序(1,2,3…)将标题保留在内容之前
// Loop over all tables
$('table').each(function() {
// Retrieve references to current table TR elements
let collection = Array.from(this.querySelectorAll('tr'))
.sort(function(x, y) {
let posX = +x.dataset.position
,posY = +y.dataset.position;
// Behavior when items haven't the same position
if (posX != posY) {
return posX > posY ? 1 : -1;
}
// When items have the same position
return x.textContent.toLowerCase().trim() == 'Title' ? 1 : -1;
})
;
// Finally move items into the container using the computed order
collection.forEach(element => {
this.querySelector('.tbody').append(element);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="deliver">
<tbody class="tbody">
<tr data-position="23">
<td>Title 23</td>
</tr>
<tr data-position="23">
<td>Content 23</td>
</tr>
<tr data-position="10">
<td>Title 10</td>
</tr>
<tr data-position="10">
<td>Content 10</td>
</tr>
<tr data-position="12">
<td>Title 12</td>
</tr>
<tr data-position="12">
<td>Content 12</td>
</tr>
</tbody>
</table>
关于javascript - jQuery 按数据位置或 id 对表 tr 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412661/