1 回答
TA贡献1859条经验 获得超6个赞
要根据需要进行排序,您需要根据值是否为数字进行不同的排序。如果两者都是数字,请像您目前所做的那样进行比较。否则,如果只有一个是数字,则将其排序到开头;如果两者都不是数字,则根据您需要的顺序 ( Open, Closed, Refurbishment) 进行排序,这可以通过在定义排序顺序的对象中查找短语来实现:
var states = {
'Open': 0,
'Closed': 1,
'Refurbishment': 2
};
$(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();
if (!isNaN(parseInt(a))) {
if (!isNaN(parseInt(b))) {
// a and b both numeric
return a.localeCompare(b, false, {
numeric: true
});
} else {
// a numeric, b not, sort b last
return 1;
}
} else if (!isNaN(parseInt(b))) {
// a not numeric, b numeric, sort a last
return -1;
} else {
// a not numeric, b not numeric, sort regular
return states[b] - states[a];
}
});
$('#mytable tbody').html(sorted)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable">
<tbody>
<tr>
<td>Challenge trails</td>
<td>Refurbishment</td>
</tr>
<tr>
<td>Camp Discovery</td>
<td>Open</td>
</tr>
<tr>
<td>Soaring</td>
<td>120 mins</td>
</tr>
<tr>
<td>Fantasia</td>
<td>20 mins</td>
</tr>
<tr>
<td>Shipwreck Shore</td>
<td>5 mins</td>
</tr>
<tr>
<td>Rex's Racer</td>
<td>105 mins</td>
</tr>
<tr>
<td>Slinky Dog</td>
<td>Closed</td>
</tr>
</tbody>
</table>
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报