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>

訪問者ごとに1行だけのテーブルの場合、この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 に答える