有些清單需要讓使用者自行調整先後順序,例如報表欄位排序、顯示規則排序。與其搬出拖曳套件,用兩個箭頭按鈕做上移/下移其實就很好用,而且對鍵盤操作更友善。
每一列帶一個自訂屬性 cid 作為唯一標記,最後一列放一對上下箭頭:
<table class="table" id="test_table">
<thead>
<tr><th>時間</th><th>詳情</th><th>操作</th></tr>
</thead>
<tbody>
<tr cid="7.0.0-2014-04-29_11-02-24_123" class="list_line">
<td>2014-04-29 11:02:24</td>
<td>詳情</td>
<td>
<span class="move_btn glyphicon glyphicon-arrow-up" move_act="up"></span>
<span class="move_btn glyphicon glyphicon-arrow-down" move_act="down"></span>
</td>
</tr>
<tr cid="7.0.0-2014-04-29_11-02-24_915" class="list_line">
<td>2014-04-28 10:00:00</td>
<td>詳情</td>
<td>
<span class="move_btn glyphicon glyphicon-arrow-up" move_act="up"></span>
<span class="move_btn glyphicon glyphicon-arrow-down" move_act="down"></span>
</td>
</tr>
</tbody>
</table>
核心只有兩招:prev().before() 把目前這列插到上一列之前;next().after() 把它插到下一列之後。順序變更後暫時加上 danger 樣式讓使用者看到「剛動過哪一列」,兩秒後移除。
<script type="text/javascript">
$(function(){
$('.move_btn').click(function(){
var move_act = $(this).attr('move_act');
$('#test_table tbody tr').removeClass('danger');
if (move_act == 'up') {
$(this).parent().parent('tr').addClass('danger')
.prev().before($(this).parent().parent('tr'));
}
else if (move_act == 'down') {
$(this).parent().parent('tr').addClass('danger')
.next().after($(this).parent().parent('tr'));
}
setTimeout("$('#test_table tbody tr').removeClass('danger');", 2000);
});
});
</script>
純前端的排序只是視覺效果,重新整理就會打回原樣。所以要在排序後蒐集每列的 cid,依目前 DOM 順序組出陣列 POST 回去:
var order = [];
$('#test_table tbody tr').each(function(i){
order.push($(this).attr('cid'));
});
$.post('/saveOrder', { order: order.join(',') });
第一,首列不該能上移、末列不該能下移,記得加上邊界判斷或把對應箭頭設為 disabled,否則 prev() 回傳空集合時操作會靜默失敗,使用者會覺得「按了沒反應」。第二,$(this).parent().parent('tr') 這種寫法依賴 DOM 層級,結構一改就壞,建議改用 $(this).closest('tr'),語意更清楚也更耐改。第三,自訂屬性 cid 在 HTML5 下應寫成 data-cid,再用 .data('cid') 取值。