0

如何使用 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 - 在添加一行后对表进行排序”中的排序代码

这是我的小提琴,它创建了一个拼图板:http: //jsfiddle.net/MacwT/

4

1 回答 1

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();
});

演示

于 2013-05-24T21:54:07.620 回答