简体   繁体   中英

Jquery sort table data with numbers

Jquery sort table data with numbers

I have sorted this table in ascending order but I want it in order of a1,a2,a3,a11.

Can anyone help, please?

 function sortTable(table, order) { var asc = order === 'asc', tbody = table.find('tbody'); tbody.find('tr').sort(function(a, b) { if (asc) { return jQuery('td:first', a).text().localeCompare(jQuery('td:first', b).text()); } else { return jQuery('td:first', b).text().localeCompare(jQuery('td:first', a).text()); } }).appendTo(tbody); } sortTable($('#mytable'),'asc'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table name="mytable" id="mytable"> <tbody> <tr><td>a 11</td></tr> <tr><td>a 3</td></tr> <tr><td>a 2</td></tr> <tr><td>a 1</td></tr> </tbody> </table> 

You can set options parameter as {numeric: true }

 var sorted = $('#mytable tbody tr').sort(function(a, b) { var a = $(a).find('td:first').text(), b = $(b).find('td:first').text(); return a.localeCompare(b, false, {numeric: true}) }) $('#mytable tbody').html(sorted) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table name="mytable" id="mytable"> <tbody> <tr><td>a 11</td></tr> <tr><td>a 3</td></tr> <tr><td>a 2</td></tr> <tr><td>a 1</td></tr> </tbody> </table> 

由于比较是从左到右完成的,因此您可以尝试用0填充数字,例如01、02、03、11

@Nenad nailed it: 'kn' does not seem to work, use option numeric in .localeCompare() like:

.localeCompare(jQuery('td:first', b).text(),'en',{numeric:true});

This will take care of the numbering problem. See here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

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