2012年6月6日 星期三

[js]jquery sort table by data attr 排序表格

[js]jquery sort table by data attr 排序表格

javascript 區段加入

$(document).ready(function() {
$('.link-sort-table1').click(function(e) {
var $sort = this;
var $table = $('#sort-table1');
var $rows = $('tbody > tr',$table);

$rows.sort(function(a, b){
var keyA = parseInt($(a).attr('data-price'));
//alert(keyA);
var keyB = parseInt($(b).attr('data-price'));
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();
});
});


HTML 區段如下

<table id="sort-table1" cellpadding="5" cellspacing="2" border="0">
<thead>
<tr>
<th align="left">Sort: <a href="#" class="link-sort-table1 asc">由小到大</a> <a href="#" class="link-sort-table1 desc">由大到小</a></th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr data-price="45"><td>Thailand</td><td align="right">45</td></tr>
<tr data-price="245"><td>Chad</td><td align="right">245</td></tr>
<tr data-price="543"><td>Liberia</td><td align="right">543</td></tr>
<tr data-price="67"><td>Guyana</td><td align="right">67</td></tr>
<tr data-price="22"><td>United States of America</td><td align="right">22</td></tr>
</tbody>
</table>





Sort Divs in Jquery Based on Attribute 'data-sort'? - Stack Overflow
http://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort
jQuery order by date in data attribute - Stack Overflow
http://stackoverflow.com/questions/7211704/jquery-order-by-date-in-data-attribute


-end- peicheng

沒有留言:

張貼留言