如何为表格每行前5个最高championshipPoints的TD添加类?
实现表格每行前5个最高分数高亮的思路指引
我有如下表格,希望为每行中class为'championshipPoints'的TD里的前5个最高值添加类。目前已实现为最高值添加类,但无法继续推进。若第6和第7个值相同,仅需高亮其中一个。希望自行解决,求几点思路指引。
现有HTML代码:
<table id="2020societyChampionship"> <tbody> <tr class='memberPoints'> <td>1</td> <td class='playerName' scope='row'>player1</td> <td class='championshipPoints'>6</td> <td class='championshipPoints'>20</td> <td class='championshipPoints'>7</td> <td class='championshipPoints'>13</td> <td class='championshipPoints'>0</td> <td class='championshipPoints'>20</td> <td class='championshipPoints'>25</td> <td class='championshipPoints'>0</td> <td class='championshipPoints'>11</td> <td class='championshipPoints'>11</td> <td class='championshipPoints'>0</td> <td>100</td> </tr> <tr class='memberPoints'> <td>1</td> <td class='playerName' scope='row'>player2</td> <td class='championshipPoints'>25</td> <td class='championshipPoints'>20</td> <td class='championshipPoints'>8</td> <td class='championshipPoints'>11</td> <td class='championshipPoints'>0</td> <td class='championshipPoints'>16</td> <td class='championshipPoints'>22</td> <td class='championshipPoints'>0</td> <td class='championshipPoints'>11</td> <td class='championshipPoints'>11</td> <td class='championshipPoints'>0</td> <td>100</td> </tr> </tbody> </table>
现有jQuery代码:
$(document).ready(function(){ $('tbody tr').each(function() { var $tds = $(this).find('.championshipPoints'); var values = $tds.map(function(){return parseFloat($(this).text());}).get(); $tds.eq(values.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0)).addClass('highestFive'); }); });
我看你已经成功实现了单个最高值的高亮,要扩展到前5个并处理并列情况,这里给你几个具体的思路方向:
第一步:给分数绑定原始位置,再排序
你现在已经能拿到每行的分数数组,但排序后会丢失原始单元格的位置信息。所以可以把每个分数和它对应的单元格索引打包成对象,再做降序排序:// 生成带索引的分数数组,同时处理非数字情况 var indexedScores = $tds.map(function(idx) { return { score: parseFloat($(this).text()) || 0, index: idx }; }).get(); // 按分数从高到低排序 indexedScores.sort((a, b) => b.score - a.score);这样排序后的数组既保留了分数大小,又能快速找到对应的单元格。
第二步:筛选出前5个需要高亮的位置
要处理并列情况,核心是找到“第5个分数的阈值”,然后只取到刚好5个符合条件的元素:- 先确定排序后第5个元素的分数(索引为4,因为从0开始)作为阈值;如果该行分数数量不足5,就取最后一个的分数。
- 遍历排序后的数组,收集符合分数≥阈值的元素,直到收集满5个就停止。
示例逻辑:
var highlightedIndices = []; var threshold = indexedScores[Math.min(4, indexedScores.length - 1)].score; for (let item of indexedScores) { if (highlightedIndices.length >= 5) break; if (item.score >= threshold) { highlightedIndices.push(item.index); } }这样即使第6个分数和第5个相同,也不会被加入高亮列表,完美符合你的需求。
第三步:批量给单元格添加高亮类
拿到需要高亮的索引数组后,直接遍历数组找到对应单元格添加类即可:highlightedIndices.forEach(idx => { $tds.eq(idx).addClass('highestFive'); });额外优化:避免重复计算
如果你表格行数很多,已经用$tds缓存每行的分数单元格是个很好的习惯,可以继续保持,减少DOM查询的开销。
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

