如何使用jQuery基于points和times多条件排序div元素
多条件排序实现:按积分降序、相同积分按用时升序
需求说明
现有代码可实现.contest_entry元素按.points数值降序排序,需要新增逻辑:当积分相同时,按.times的时间从小到大排序(用时更短的排在前面)。
修改后的完整代码
JavaScript 代码
$(function(){ var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){ // 解析积分值,去除空格避免解析异常 const lhsPoints = parseInt($(lhs).children("span.points").text().trim(), 10); const rhsPoints = parseInt($(rhs).children("span.points").text().trim(), 10); // 优先按积分降序比较 const pointsDiff = rhsPoints - lhsPoints; if (pointsDiff !== 0) { return pointsDiff; } // 积分相同时,将时间转为总分钟数做升序比较 const parseTimeToMinutes = (timeStr) => { const [hours, minutes] = timeStr.trim().split(':').map(Number); return hours * 60 + minutes; }; const lhsTime = parseTimeToMinutes($(lhs).children("span.times").text()); const rhsTime = parseTimeToMinutes($(rhs).children("span.times").text()); return lhsTime - rhsTime; }); $("#list").html(sortedList); });
CSS 代码(无需修改)
.contest_entry { padding:10px; background: #eee; margin:10px 0px; } .points { display:block; }
HTML 代码(无需修改)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <div id="list"> <div class="contest_entry"> <span class="points">14</span> <span class="times"> 12:39 </span> </div> <div class="contest_entry"> <span class="points">16</span> <span class="times"> 09:55 </span> </div> <div class="contest_entry"> <span class="points">19</span> <span class="times"> 17:19 </span> </div> <div class="contest_entry"> <span class="points">19</span> <span class="times"> 17:34 </span> </div> <div class="contest_entry"> <span class="points">19</span> <span class="times"> 17:20 </span> </div> </div>
逻辑说明
- 积分排序优先级:先提取每个元素的积分值转为整数,通过
rhsPoints - lhsPoints实现降序排序,积分高的元素优先靠前 - 时间排序(积分相同时):通过辅助函数
parseTimeToMinutes将HH:MM格式的时间转为总分钟数,再通过lhsTime - rhsTime实现升序排序,保证用时更短的元素排在前面 - 鲁棒性处理:对文本内容做
trim()操作,避免前后空格影响数值解析
内容的提问来源于stack exchange,提问作者Md. Ibrahim
相关产品推荐
相关产品推荐

