Сортировка таблицы по атрибуту
Есть таблица
<table> <tbody> <tr> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="8"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="12"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="2"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="7"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> </tbody> </table> Нужно ее строки отсортировать по параметру data-sort, по убыванию, чтоб было так: <table> <tbody> <tr data-sort="12"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="8"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="7"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="2"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> <tr> <th>cell 1</th> <th>cell 2</th> </tr> </tbody> </table> Как это сделать наиболее лучшим или простым способом? (с помощью jquery) |
Sanu0074,
:-? <!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $(function(){ var arr = $.makeArray( $("tbody tr") );; arr.sort(function(a, b) { a = $(a).data('sort')!== void(0)? +$(a).data('sort'):-1 ; b = $(b).data('sort')!== void(0)? +$(b).data('sort') : -1 ; return b - a }); $( arr ).prependTo("tbody"); alert($("body").html()) }); </script> </head> <body> <table> <tbody> <tr> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="8"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="12"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="2"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="7"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> <tr data-sort="0"> <th>cell 1</th> <th>cell 2</th> </tr> </tbody> </table> </body> </html> |
рони,
спасибо) |
Часовой пояс GMT +3, время: 02:01. |