本文详解如何使用 jquery 对 `.contest_entry` 元素进行多级排序:优先按 `span.points` 数值**降序**(高分在前),分数相同时再按 `span.times` 字符串**升序**(早时间在前),并提供可直接运行的完整代码与关键注意事项。
在实际前端开发中,仅按单一字段排序往往无法满足业务需求。例如竞赛排行榜需“先看得分高低,得分相同再比用时长短”——这正是典型的多条件复合排序场景。jQuery 本身不内置多字段排序方法,但可通过 Array.prototype.sort() 的比较函数灵活实现。
核心逻辑如下:
用了 .find(".child span.points"),而示例 HTML 中并无 .child 容器,应修正为 .find("span.points")。以下是修复并优化后的完整可运行代码:
$(function() {
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs) {
var lhsPoints = parseInt($(lhs).find('span.points').text().trim(), 10);
var rhsPoints = parseInt($(rhs).find('span.points').text().trim(), 10);
if (lhsPoints === rhsPoints) {
// 时间字符串去空格后比较(HH:MM 格式支持直接字符串比较)
var lhsTime = $(lhs).find('span.times').text().trim();
var rhsTime = $(rhs).find('span.times').text().trim();
return lhsTime > rhsTime ? 1 : -1;
} else {
return rhsPoints - lhsPoints; // 降序:高分在前
}
});
$("#list").html(sortedList);
});✅ 关键注意事项:
最终排序结果将严格遵循:19分(17:19 → 17:20 → 17:34)→ 16分 → 14分,完全符合“高分优先、同分比快”的业务规则。