简体   繁体   English

如何使用JavaScript对数字HTML表格列进行排序

[英]How to Sort a numeric HTML table column at defult using javascript

I have this table 我有这张桌子

   <table name="mytable" id="mytable">
      <tbody>
        <tr>
        <th>Name</th>
        <th>Age</th>
        <th>LastName</th>
        </tr>
        <tr>
        <td>Dean</td>
        <td>18</td>
        <td>Tank</td>
        </tr>
        <tr>
        <td>Jean</td>
        <td>3</td>
        <td>Ted</td>
        </tr>
        <tr>
        <td>Frank</td>
        <td>11</td>
        <td>Marie</td>
        </tr>
        <tr>
        <td>Kid</td>
        <td>8</td>
        <td>Arnold</td>
        </tr>
        <tr>
        <td>Ted</td>
        <td>9</td>
        <td>Marie</td>
        </tr>
        <tr>
        <td>Ma</td>
        <td>10</td>
        <td>Jack</td>
        </tr>
        <tr>
        <td>Martin</td>
        <td>7</td>
        <td>Harvey</td>
        </tr>
        <tr>
        <td>Nelson</td>
        <td>16</td>
        <td>Tom</td>
        </tr>
      </tbody>
    </table>

So I'm trying to display it with the column age sorted in descending order. 因此,我尝试使用按降序排列的列年龄来显示它。 I have not found any solution to this. 我还没有找到任何解决方案。 The solutions I have found seem to be for alphabetic columns. 我发现的解决方案似乎是针对字母列的。

The biggest problem is actually having the table displayed with the column Age already sorted in descending order without the user having to tap on a header or button to sort it. 最大的问题实际上是使显示的表中“ 年龄 ”列已按降序排序,而用户不必点击标题或按钮即可对其进行排序。

I was able to find a solution using this script 我可以使用此脚本找到解决方案

<script>
function sortTable(){
var sorted = $('#myTable tbody tr').sort(function(a, b) {
  var a = $(a).find('td:first-child + td').text(), b = $(b).find('td:first-child + td').text();
  return b.localeCompare(a, false, {numeric: true})
})

$('#myTable').html(sorted);
}
sortTable();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM