如何使用纯 jquery 对数字和字符串进行 asc 和 desc 进行表排序。我尝试使用下面的代码如下。在这里,它适用于数值的降序顺序,然后我再次单击它,它不起作用,仅显示为降序顺序,而不是升序顺序。 谁能帮忙..
<table class="table table-hover" style="width:96%;margin:2%;margin-top:0%" id="patientTable">
<thead id="theader">
<tr style="background-color: #5bc0de/*rgb(255, 106, 106)*/;color: #F6F4F4;font-size:12.999999px">
<th>Name</th>
<th>Pati</th>
<th>Device Status</th>
<th>Monitoring Status</th>
<th>Monitoring Mode</th>
<th>Service Start</th>
<th>Service End</th>
</tr>
</thead>
<tbody>
<tr>
<td>agesh1</td>
<td>4535324</td>
<td>With Patient, Inactive</td>
<td>Service Ended</td>
<td>HOLTER</td>
<td>24 Dec , 2014</td>
<td>26 Dec , 2014</td>
</tr>
<tr>
<td>ragesh</td>
<td>2345457</td>
<td>With Patient, Inactive</td>
<td>Service Ended</td>
<td>HOLTER</td>
<td>24 Dec , 2014</td>
<td>26 Dec , 2014</td>
</tr>
<tr>
<td>abcde name</td>
<td>123423</td>
<td>With Patient, Inactive</td>
<td>Service Ended</td>
<td>HOLTER</td>
<td>24 Dec , 2014</td>
<td>26 Dec , 2014</td>
</tr>
</tbody>
</table>
$(document).ready(function () {
$('#patientTable thead th:eq(0)').click(function () {
sorttable();
});
});
function sorttable() {
var $tbody = $('table tbody');
$tbody.find('tr').sort(function (a, b) {
var tda = $(a).find('td:eq(0)').text();
var tdb = $(b).find('td:eq(0)').text();
return tda > tdb ? 1
: tda < tdb ? -1
: 0;
}).appendTo($tbody);
}
最佳答案
您可以做一些小改变:
$(document).ready(function() {
$('#patientTable thead th').click(function(){
//Add parameter for remembering order type
$(this).attr('data-order', ($(this).attr('data-order') === 'desc' ? 'asc':'desc'));
//Add aditional parameters to keep track column that was clicked
sorttable(this, $('#patientTable thead th').index(this));
});
});
function sorttable(header, index){
var $tbody = $('table tbody');
var order = $(header).attr('data-order');
$tbody.find('tr').sort(function (a, b) {
var tda = $(a).find('td:eq(' + index + ')').text();
var tdb = $(b).find('td:eq(' + index + ')').text();
//Order according to order type
return (order === 'asc' ? (tda > tdb ? 1 : tda < tdb ? -1 : 0) : (tda < tdb ? 1 : tda > tdb ? -1 : 0));
}).appendTo($tbody);
}
查看自fiddle
关于javascript - 使用带有 asc 和 desc 的纯 jquery 进行表排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28714159/