javascript - 表格按 JavaScript 中的总列排序
问题描述
我正在尝试按总值对表格进行排序。链接。这可行,但是当两个表元素具有相同的点时它会失败。
我正在尝试使用 javascript 对表格进行排序,以便在最后按总分排序。该表是动态表,因此 W1、W2、W3 列加起来为总数。每一行也是动态创建的。
请帮忙
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];
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onClick="sortTotal()">
Sort</button>
</button>
<table class="fl-table">
<thead>
<tr>
<th>Player</th>
<th>Player Name</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/70C/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/70C/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/70C/O https://placeholder.com/"></td>
<td>Latheesh V M V</td>
<td>2</td>
<td>26</td>
<td>4</td>
</tr>
</tbody>
</table>
解决方案
您按错误的列排序。
a[a.length -2] > b[b.length -2]
应该是
a[a.length -1] > b[b.length -1]
并且 sort 总共会产生 25、4、4
推荐阅读
- python - Tabula 未正确排序提取的表
- javascript - 我有不会添加的数字(我必须保留为字符串)。他们只是连接数字
- git - 新签出时 cygwin 文件上的 git 已更改
- regex - 第 N 个非空白正则表达式匹配
- c# - C#如何从包含具有不同编码的多个文件的文件夹中读取文本
- java - 当我向它添加 actionListener 时,为什么我的按钮会从边框布局中消失?
- sql - SQL Server - 连接前 5 行
- javascript - 检查平板电脑是否与设备的操作系统无关
- c++ - 无法取消引用超出范围的向量迭代器 - 有什么问题?
- google-app-maker - 从表格小部件中的第一条记录中删除焦点?