如何使用带有asc和desc的纯jquery对数字和字符串进行表排序。我尝试使用下面的代码。这里它正在为数字值的desc顺序工作,然后我再次点击它不工作显示像desc顺序只是不在asc顺序.. 可以任何人帮助..
<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);
}
答案 0 :(得分:1)
您可以做一些小改动:
$(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);
}
查看