使用javascript或jquery根据表头列对表格行进行排序 [英] Sorting table rows according to table header column using javascript or jquery
本文介绍了使用javascript或jquery根据表头列对表格行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类似的东西
<table><thead>
<tr>
<th>S.L.</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ronaldo</td>
</tr>
<tr>
<td>2</td>
<td>Messi</td>
</tr>
<tr>
<td>3</td>
<td>Ribery</td>
</tr>
<tr>
<td>4</td>
<td>Bale</td>
</tr>
</tbody>
</table>
我想要的是将< tr>
< tbody>
点击 th
时,按升序和降序交替依次显示 th
点击。
What i want is to sort the <tr>
of <tbody>
when clicked th
in ascending and descending order alternatively in according to the following th
clicked.
- 如果点击
SL
th
然后它显示
中的表格行降序,然后在每次点击时以升序排列。 - 当点击
名称
th
时,它应该显示名称,按降序排列
,然后按升序排列在他们各自的
SL
- so if some one clicks the
S.L
th
then it shows the table rows in descending and then ascending order alternatively at every click. - When clicked
Name
th
it should show the names in descending order and then ascending order without change in their respectiveS.L
这里是小提琴
推荐答案
希望看到此页面:
http://blog.niklasottosson.com/? p = 1914
我想你可以这样做:
DEMO: http://jsfiddle.net/g9eL6768/2 /
HTML:
HTML:
<table id="mytable"><thead>
<tr>
<th id="sl">S.L.</th>
<th id="nm">name</th>
</tr>
....
JS:
JS:
// sortTable(f,n)
// f : 1 ascending order, -1 descending order
// n : n-th child(<td>) of <tr>
function sortTable(f,n){
var rows = $('#mytable tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a);
var B = getVal(b);
if(A < B) {
return -1*f;
}
if(A > B) {
return 1*f;
}
return 0;
});
function getVal(elm){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseInt(v,10);
}
return v;
}
$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
f_sl *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_sl,n);
});
$("#nm").click(function(){
f_nm *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_nm,n);
});
希望这有助于您。
这篇关于使用javascript或jquery根据表头列对表格行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文