Jquery 排序表 -> 文本前的数字

我正在开发一个等待时间 API 来显示迪士尼乐园的当前排队时间。等待时间按字母顺序加载到表中。


现在,我使用以下代码将此表按表顶部的最高等待时间排序为最低等待时间。这就是我想要的:


$(document).ready(function(){

var sorted = $('#mytable tbody tr').sort(function(b, a) {

  var a = $(a).find('td:last').text(), b = $(b).find('td:last').text();

  return a.localeCompare(b, false, {numeric: true})

})


$('#mytable tbody').html(sorted)

});

这很好用,但正如您在下图中看到的那样,“已关闭”和“翻新”等文本值位于表格顶部,高于最长等待时间。


我如何更改表格的顺序以获得表格顶部的最长等待时间,最后是文本值?


当前订单,想要更改此


所以我想得到:


20 min.

15 min.

5 min.

Open

Closed

Refurbishment


胡子哥哥
浏览 111回答 1
1回答

BIG阳

要根据需要进行排序,您需要根据值是否为数字进行不同的排序。如果两者都是数字,请像您目前所做的那样进行比较。否则,如果只有一个是数字,则将其排序到开头;如果两者都不是数字,则根据您需要的顺序 ( Open, Closed, Refurbishment) 进行排序,这可以通过在定义排序顺序的对象中查找短语来实现:var states = {&nbsp; 'Open': 0,&nbsp; 'Closed': 1,&nbsp; 'Refurbishment': 2};$(document).ready(function() {&nbsp; var sorted = $('#mytable tbody tr').sort(function(b, a) {&nbsp; &nbsp; var a = $(a).find('td:last').text(),&nbsp; &nbsp; &nbsp; b = $(b).find('td:last').text();&nbsp; &nbsp; if (!isNaN(parseInt(a))) {&nbsp; &nbsp; &nbsp; if (!isNaN(parseInt(b))) {&nbsp; &nbsp; &nbsp; &nbsp; // a and b both numeric&nbsp; &nbsp; &nbsp; &nbsp; return a.localeCompare(b, false, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numeric: true&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // a numeric, b not, sort b last&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if (!isNaN(parseInt(b))) {&nbsp; &nbsp; &nbsp; // a not numeric, b numeric, sort a last&nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; // a not numeric, b not numeric, sort regular&nbsp; &nbsp; &nbsp; return states[b] - states[a];&nbsp; &nbsp; }&nbsp; });&nbsp; $('#mytable tbody').html(sorted)});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table id="mytable">&nbsp; <tbody>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Challenge trails</td>&nbsp; &nbsp; &nbsp; <td>Refurbishment</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Camp Discovery</td>&nbsp; &nbsp; &nbsp; <td>Open</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Soaring</td>&nbsp; &nbsp; &nbsp; <td>120 mins</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Fantasia</td>&nbsp; &nbsp; &nbsp; <td>20 mins</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Shipwreck Shore</td>&nbsp; &nbsp; &nbsp; <td>5 mins</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Rex's Racer</td>&nbsp; &nbsp; &nbsp; <td>105 mins</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>Slinky Dog</td>&nbsp; &nbsp; &nbsp; <td>Closed</td>&nbsp; &nbsp; </tr>&nbsp; </tbody></table>
打开App,查看更多内容
随时随地看视频慕课网APP