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

问题描述 投票:4回答:1

我有下表,并希望在加载页面后根据<th>位置属性值和jquery重新排序表列。

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

  1. jQuery re-ordering table columns
  2. Re-order table columns?
  3. Change table columns order

<table>
    <head>
        <tr>
            <th position = "3">Email</th>
            <th position = "1">Name</th>
            <th position = "2">Phone</th>
        </tr>
    </head>
    <tbody>
        <tr>
            <td>[email protected]</td>
            <td>Hamid</td>
            <td>0776567432</td>
        </tr>
    </tbody>
</table>

预期结果:enter image description here

jquery datatables
1个回答
2
投票

使用<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>[email protected]</td>
            <td>Hamid</td>
            <td>0776567432</td>
        </tr>
    </tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.