【问题标题】:Get Table Row Pairs and Sort with JQuery获取表行对并使用 JQuery 进行排序
【发布时间】:2013-05-26 15:20:31
【问题描述】:

如何使用 javascript 或 jquery 将表中的行成对地放入变量中?之后我想在桌子上做一个简单的排序。

<table>
 <thead>
    <tr>
        <th rowspan="2">Visitor</th>
        <td>Scheduled In</td>
        <td>Time In</td>
    </tr>
    <tr>
        <td>Scheduled Out</td>
        <td>Time Out</td>
    </tr>
</thead>
<tbody>
    <tr>
        <th rowspan="2">Santos Angelo Borodec</th>
        <td>9am</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>5pm</td>
        <td>&nbsp;</td>
    </tr>
  ...
  </tbody>
</table>

对于每个访问者只有一行的表格,我有这个可以工作的 javascript。

$('.sort-table').click(function(e) {
    var $sort = this;
    var $table = $('#sort-table');
    var $rows = $('tbody > tr',$table);
    $rows.sort(function(a, b){
        var keyA = $('th',a).text();
        var keyB = $('th',b).text();
        if($($sort).hasClass('asc')){
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA > keyB) ? 1 : 0;
        }
    });
    $.each($rows, function(index, row){
      $table.append(row);
    });
    e.preventDefault();
});

通过选择像tr:nth-child(4n), tr:nth-child(4n-1) 这样的行对我不起作用。

有没有一种简单的方法可以做到这一点?

这是基于“jQuery - sort a table after adding a row to it”中的排序代码

这是我用来制作拼图板的小提琴:http://jsfiddle.net/MacwT/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    尝试这种方法对tr 对进行排序。

    $('.sort-table').click(function (e) {
        var $sort = this;
        var $table = $('#sort-table');
    
       //Find the even rows and its next one, clone and wrap them into temp table.
        var $rows = $table.find('tbody > tr:even').map(function () {
            return $(this).next().andSelf().clone().wrapAll('<table />')
        }); 
      //Give each table which contains the pair to be sorted
        $rows.sort(function (a, b) {
            var keyA = $('th', a).text();
            var keyB = $('th', b).text();
            if ($($sort).hasClass('asc')) {
                return (keyA > keyB) ? 1 : 0;
            } else {
                return (keyA > keyB) ? 1 : 0;
            }
        });
    
        var tbody = $('tbody', $table).empty();//empty the tbody
        $.each($rows, function (index, row) {
            $(tbody).append($(row).unwrap());//Unwrap the table and get the rows alone.
        });
        e.preventDefault();
    });
    

    Demo

    【讨论】:

    • 谢谢!这是一个很好的解决方案,不需要对原始代码进行太多修改。
    猜你喜欢
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2013-07-21
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多