0

嗨,我有下面的代码我想根据类名对表行进行排序..这里每行包含两个类,一个是“sprint1”,第二个是“cls *”..我想根据第二个对行进行排序类...提前谢谢

   <tr class="sprint1 cls5">

   <tr class="sprint1 cls4">

   <tr class="sprint1 cls3">

   <tr class="sprint1 cls1">

   <tr class="sprint1 cls2">

4

4 回答 4

1

用于Array.sort对类进行排序,然后根据该对行重新排序。

http://jsfiddle.net/jamietre/eyr4N/

    var i, 
        table = $('table'),
        rows = $('tr'),
        classes = [];

    // build an array from the 2nd item in the class list on each row

    rows.each(function(i, e) {
        classes.push(e.className.split(' ')[1]);
    });

    // sort the array

    classes.sort();

    // reorganize the rows by adding each one again to the table, in the order of the
    // sorted class list. ("Adding" it with jquery append will move it to the end).

    for (i = 0; i < classes.length; i++) {
        table.append(table.find('tr.' + classes[i]));
    }
于 2012-08-29T13:28:52.883 回答
1

您可以array根据class名称制作并替换tr元素。

var arr = [];
$('tr[class*="cls"]').each(function(i, v){
    var ind = this.className.slice(-1)
    arr[ind-1] = this.outerHTML
})    
$('table').html(arr.join(""))   
// or $('table tbody').html(arr.join(""))       

小提琴

于 2012-08-29T13:30:09.480 回答
0

使用排序方法..

var x = $('tr'); // <-- get all tr 
x.sort(function(a,b) {
    // split class name at cls and get the number after to sort with
    return $(a).attr('class').split('cls')[1] - $(b).attr('class').split('cls')[1];
});
// remake the table with new sorted tr
$('table > tbody').html(x);

http://jsfiddle.net/UTXUY/1/

于 2012-08-29T13:37:16.030 回答
-1

尝试使用 jQuery.dataTables ......它提供了分页和排序选项,包括这个

   <link href="css/demo_page.css" rel="stylesheet" id="stylesheet"/>
      <link href="css/demo_table.css" rel="stylesheet" />
     <script  src="js/jquery.dataTables.js"></script>

并声明表格

      <table id="abc" class="display">
          ...
       </table>

jQuery 调用:

        $('#abc').dataTable({

        "iDisplayLength": 5,

           });
于 2012-08-29T13:21:45.333 回答