jQuery对多个Tbody进行排序 [英] Jquery Sort multiple Tbody
本文介绍了jQuery对多个Tbody进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张这样的桌子:
<table>
<thead>
<tr>
<th>Department</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<th>Data</th>
<th>100</th>
</tr>
<tr>
<td>DTP</td>
<td>20</td>
</tr>
<tr>
<td>VTP</td>
<td>30</td>
</tr>
<tr>
<td>RTP</td>
<td>50</td>
</tr>
</tbody>
<tbody>
<tr>
<th>Testing</th>
<th>100</th>
</tr>
<tr>
<td>QTP</td>
<td>20</td>
</tr>
<tr>
<td>ATP</td>
<td>30</td>
</tr>
<tr>
<td>CTP</td>
<td>50</td>
</tr>
</tbody>
</table>
当我单击部门标题时,应该对内部数据和测试进行排序.但是数据和测试TH
应该保持不变.
When I click department header, tr
inside data and testing should get sorted. But data and testing TH
should remain the same.
我不想使用任何jQuery插件.请共享代码以完成此任务.
I don't want to use any jQuery plugin. Kindly share code to do this task.
推荐答案
这是一个快速实现.希望您会改进它并满足您的需求:
Here is a quick implementation. Hopefully you will improve it and it will match your needs:
var $table = $('table'),
$th = $table.find('thead th'),
$tbody = $table.find('tbody');
$th.on('click', function() {
$th.removeClass();
var index = this.cellIndex,
sortType = $(this).data('sort'),
sortDir = $(this).data('dir') || 'asc';
$tbody.each(function() {
$(this).find('tr').slice(1).sort(function(a, b) {
var aText = $(a).find('td:eq(' + index + ')').text(),
bText = $(b).find('td:eq(' + index + ')').text();
if (sortDir == 'desc') {
temp = aText;
aText = bText;
bText = temp;
}
if (sortType == 'string') {
return aText.localeCompare(bText);
}
else {
return +aText - +bText;
}
})
.appendTo(this);
});
$(this).data('dir', sortDir == 'asc' ? 'desc' : 'asc');
$(this).removeClass().addClass('sort-' + sortDir);
});
这篇关于jQuery对多个Tbody进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文