使用javascript或jquery根据表头列对表行进行排序 [英] Sorting table rows according to table header column using javascript or 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>
我想要的是对 What i want is to sort the 这里是小提琴 您可能希望看到此页面: You might want to see this page: 我想你可以这样做: 演示:http://jsfiddle.net/g9eL6768/2/ HTML: JS: 希望这会有所帮助. 这篇关于使用javascript或jquery根据表头列对表行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 的
当点击 th
时按升序和降序交替排序按照下面的th
点击.
<tr>
of <tbody>
when clicked th
in ascending and descending order alternatively in according to the following th
clicked.S.L
th
然后它会显示表格行每次点击时交替进行降序和升序.Name
th
时,它应该以降序显示名称顺序然后升序而不改变它们各自的S.L
S.L
th
then it shows the table rows in
descending and then ascending order alternatively at every click.Name
th
it should show the names in descending
order and then ascending order without change in their respective
S.L
推荐答案
http://blog.niklasottosson.com/?p=1914
http://blog.niklasottosson.com/?p=1914 <table id="mytable"><thead>
<tr>
<th id="sl">S.L.</th>
<th id="nm">name</th>
</tr>
....
// 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);
});
登录
关闭