如何在jquery中重新排序表列位置

Kha*_*zad 7 jquery datatables

<th>我有下表,想在页面加载后根据position属性值用jquery对表列重新排序。

我查看了以下解决方案,但无法解决我的问题:

  1. jQuery 对表列重新排序
  2. 重新排序表列?
  3. 更改表列顺序

<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>
Run Code Online (Sandbox Code Playgroud)

预期结果: 在此输入图像描述

cha*_*tfl 6

使用索引作为键从位置属性创建一个对象<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;
    });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)