使用javascript或jquery根据表头列对表行进行排序 [英] Sorting table rows according to table header column using javascript or jquery

查看:20
本文介绍了使用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>

我想要的是对 当点击 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.

  1. 所以如果有人点击 S.L th 然后它会显示表格行每次点击时交替进行降序和升序.
  2. 当点击Name th 时,它应该以降序显示名称顺序然后升序而不改变它们各自的S.L
  1. 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.
  2. When clicked 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

You might want to see this page:
http://blog.niklasottosson.com/?p=1914

我想你可以这样做:

演示:http://jsfiddle.net/g9eL6768/2/

HTML:

 <table id="mytable"><thead>
  <tr>
     <th id="sl">S.L.</th>
     <th id="nm">name</th>
  </tr>
   ....

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆