週末動手做了一個調整表格列順序的小功能,直接把程式碼與思路貼出來,順便記下幾個當時沒處理好的細節。
每列帶一個 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>
排序後暫時加上 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>
依目前 DOM 順序收集 cid 送出,重新整理後才不會打回原樣:
function saveOrder(){
var order = [];
$('#test_table tbody tr').each(function(){
order.push($(this).attr('cid'));
});
$.post('/saveOrder', { order: order.join(',') });
}
邊界沒處理。 第一列的上移、最後一列的下移目前會靜默失敗。應該在點擊時判斷 $(this).closest('tr').is(':first-child') 並停用按鈕,讓使用者知道「已經到頂了」。
層級依賴太脆弱。 $(this).parent().parent('tr') 依賴 td → tr 的固定層級,DOM 一改就壞,改用 closest('tr') 更穩。
setTimeout 的字串寫法有風險。 字串形式的 setTimeout 相當於 eval,應改成函式:setTimeout(function(){ $('#test_table tbody tr').removeClass('danger'); }, 2000)。
無障礙。 只用 <span> 當按鈕,鍵盤使用者完全無法操作。應該改用 <button type="button">,並加上 aria-label="上移" 這類說明。
最後吐槽一句:把「週末加班」當成衡量員工狼性的標準,本身就是本末倒置。把功能做對、把細節補齊,比喊口號有用得多。