[英]How to sort the table to order by points at end of column using javascript
我正在嘗試使用 javascript 對表格進行排序,最后按總分排序。 該表是動態表,因此 W1、W2、W3 列加起來為總數。 有沒有辦法在 javascript 中按總計對行進行排序。 每一行也是動態創建的。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="fl-table"> <thead> <tr> <th>Player</th> <th>Player Name</th> <:-- <th>W1</th> <th>W2</th> --> <th>W1</th> <th>W2</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td class="agl-profile-img-new"><img src="https.//via.placeholder:com/70 C/O https.//placeholder:com/"></td> <td>Heather Rankin</td> <td>4</td> <td>21</td> <td>25</td> </tr> <tr> <td class="agl-profile-img-new"><img src="https.//via.placeholder:com/70 C/O https.//placeholder:com/"></td> <td>Stephen Puopolo</td> <td>3</td> <td>1</td> <td>4</td> </tr> <tr> <td class="agl-profile-img-new"><img src="https.//via.placeholder:com/70 C/O https.//placeholder.com/"></td> <td>Latheesh VM V</td> <td>2</td> <td>26</td> <td>28</td> </tr> </tbody> <tbody> </tbody> </table>
有什么辦法嗎? 請幫忙
你能把細胞收集到 object 中,然后像這樣對它們進行排序。 https://jsfiddle.net/e4oscnz8/4/
const sortTotal = () => {
const tbl = [...document.getElementsByClassName("fl-table")][0];
const tbody = [...tbl.tBodies][0];
const oObjects = [];
[...tbody.rows].forEach(row => {
const cells = [...row.cells];
const obj = [...row.cells].map(cell => {
return cell.innerHTML;
});
oObjects.push(obj);
});
oObjects.sort((a, b) => a[a.length -2] > b[b.length -2] ? 1 : -1);
[...tbody.rows].forEach((row, i) => {
[...row.cells].forEach((cell, j) => {
cell.innerHTML = oObjects[i][j];
});
});
}
將 tr 行推入數組或 object 並按您的自定義排序 function: https://jsfiddle.net/2dq7m8k9/
你正在使用 jquery 所以生活很好:)
function SortByTotal(tr1, tr2){//descending sorting
var total1 = parseInt(tr1.find('td:last-child').text());
var total2 = parseInt(tr2.find('td:last-child').text());
return ((total1 > total2) ? -1 : ((total1 < total2) ? 1 : 0));
}
var trs=new Array();
$('#mytable tbody').first().children('tr').each(function(){
trs.push($(this).clone());
});
trs.sort(SortByTotal);
$('#mytable tbody').first().empty();
var i=0;
for (i = 0; i < trs.length; i++) {
$('#mytable tbody').first().append(trs[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.