简体   繁体   中英

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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