我有下表,想要根据 <th>
对表列重新排序页面加载后使用jquery的position属性值。
我查看了以下解决方案,但无法解决我的问题:
<table>
<head>
<tr>
<th position = "3">Email</th>
<th position = "1">Name</th>
<th position = "2">Phone</th>
</tr>
</head>
<tbody>
<tr>
<td>Ali@gmail.com</td>
<td>Hamid</td>
<td>0776567432</td>
</tr>
</tbody>
</table>
最佳答案
使用<th>
从位置属性创建一个对象索引作为键。
然后在 sort()
中使用该对象回调以查找每个元素的新顺序
const colOrder = {}
$('thead th').each(function(i){
colOrder[i] = parseInt( $(this).attr('position') );
});
$('tr').html(function(i){
return $(this).children().sort(function(a,b){
const aOrder = colOrder[$(a).index()],
bOrder = colOrder[$(b).index()];
return aOrder - bOrder;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th position = "3">Email</th>
<th position = "1">Name</th>
<th position = "2">Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ali@gmail.com</td>
<td>Hamid</td>
<td>0776567432</td>
</tr>
</tbody>
</table>
关于jquery - 如何在jquery中重新排序表列位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55322221/