在後台管理介面裡,「點一下就能改」的輸入體驗,比層層跳轉的表單友善得多。本文以一個欄目排序欄位為例,把單擊修改拆成六個步驟,逐步說明背後在做什麼。
<tr>
<td><span class="catid">2</span></td>
<td>公司介紹</td>
<td>內部欄目</td>
<td><span class="listorder" title="點擊修改">2</span></td>
</tr>
步驟一:點擊排序數字,從同一列的第一欄取出欄目 id,作為後續更新的依據。
步驟二:把排序數字暫存到變數,再將畫面上的數字清空。
步驟三:在該欄位插入 text input,填入原值並設定焦點,讓使用者可以直接打字。
步驟四:輸入框失焦時,以 POST 方式透過 Ajax 把新值送到後端。
步驟五:傳輸期間顯示「修改中」提示或等待圖示,讓使用者知道系統正在處理。
步驟六:收到成功回應後,用新值覆寫畫面內容並移除輸入框。
$('.listorder').click(function(e){
var catid = $(this).parent().siblings("td:eq(0)").text(); // 同列第一欄的 id
var listorder_now_text = $(this).text(); // 暫存原值
$(this).text(""); // 清空
var list_form = '<input type="text" value="' + listorder_now_text + '" size="2" class="listorder_input" />';
$(this).parent().append(list_form); // 插入輸入框
$(".listorder_input").focus();
var loading = '<div id="loading"><img src="img/loading.gif" alt="修改中..."/></div>';
$(this).parent().append(loading);
$('#loading').css({ "color": "red", "display": "none" });
$(this).ajaxStart(function(){ $('#loading').show(); }); // 全域事件
$(this).ajaxStop(function(){ $('#loading').remove(); });
$(".listorder_input").blur(function(){
var thislist = $(this).siblings(); // 要回寫的目標
$.post("ajax.php", {
action : "mod_listorder",
catid : catid,
listorder : $(this).attr("value")
}, function(data, textStatus){
$(thislist).text(data);
});
$(this).remove();
});
});
sleep(1); // 延遲一秒,方便觀察等待效果;正式環境不需要 echo $_POST['listorder'];
程式裡取「同列第一欄」靠的是 parent().siblings("td:eq(0)"),回寫時則用 $(this).siblings() 找到原本顯示數字的 span。這種相對定位的寫法,讓同一份程式碼能套用到表格中的任意一列,不必為每一列產生專屬 id。
需要留意的是,回寫內容若直接取自伺服器回應,務必確認後端已做輸出轉義;另外全域的 ajaxStart/ajaxStop 在多請求並行時會互相覆蓋,正式環境建議收斂成局部狀態控制。