简体   繁体   English

如何按数字对表格列进行排序? (仅javascript)

[英]How to sort table column as number? (only javascript)

I need to sort this table but Percentage and Numbers columns are sorting in a strange way. 我需要对该表进行排序,但“百分比”和“数字”列却以一种奇怪的方式进行排序。 It's sorting them as strings, not numbers. 它会将它们排序为字符串,而不是数字。 I googled a lot and tried to use parseInt, parseFloat and number but the code below is the best I could get. 我在Google上搜索了很多,并尝试使用parseInt,parseFloat和number,但是下面的代码是我能得到的最好的代码。

Any way I could convert only these columns (and not the name column) to numbers? 以任何方式我只能将这些列(而不是名称列)转换为数字?

Sorry if it's too noob of a question, I'm a beginner in coding. 抱歉,如果您对这个问题不太了解,那么我是编码方面的初学者。 :-/ :-/

 var tabela, asc1 = 1, asc2 = 1, asc3 = 1; window.onload = function() { tabela = document.getElementById("table"); } function sort_table(tbody,col,asc) { var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen; for (i=0 ; i<rlen ; i++){ cells = rows[i].cells; clen = cells.length; arr[i] = new Array; for( j=0; j<clen ; j++){ arr[i][j] = cells[j].innerHTML; } } arr.sort( function(a, b){ return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc); }); for (i=0; i<rlen ; i++){ rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>"; } } 
 <table class="table"> <thead> <th onclick="sort_table(table,0,asc1);asc1 *= -1;asc2 = 1; asc3 = 1;">Number</th> <th onclick="sort_table(table,1,asc2);asc2 *= -1;asc1 = 1; asc3 = 1;">Name</th> <th onclick="sort_table(table,2,asc3);asc3 *= -1;asc1 = 1; asc2 = 1;">Percentage</th> </thead> <tbody id="table"> <tr> <td>1</td> <td>A</td> <td>10%</td> </tr> <tr> <td>5</td> <td>D</td> <td>55%</td> </tr> <tr> <td>3</td> <td>F</td> <td>3%</td> </tr> </tbody> </table> 

var sortVal = cells[j].innerHTML;
arr[i][j] = isNaN(sortVal) ? sortVal : sortVal/1;

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

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