後台表格裡的排序數字、狀態欄位,若每次修改都要跳轉到編輯頁,操作起來相當繁瑣。「單擊即改」的做法是:點一下文字,原地變成輸入框,離開時自動送出並更新畫面。以下用欄目排序為例,拆解整個流程。
<tr>
<td><span class="catid">2</span></td>
<td>公司介紹</td>
<td>內部欄目</td>
<td><span class="listorder" title="點擊修改">2</span></td>
</tr>
1. 點擊排序數字,先取得同一列第一欄的內容,也就是欄目 id。
2. 把原本的數字暫存起來,然後清空該元素。
3. 在同一個 td 中插入 input,帶入原值並聚焦。
4. input 失焦時,以 POST 方式透過 Ajax 送出修改。
5. 送出期間顯示「修改中」的等待提示。
6. 收到回應後寫回新值,並移除 input。
$('.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); // 延遲一秒方便觀察 loading 效果,實作時可移除 echo $_POST['listorder'];
第一,ajaxStart 與 ajaxStop 是全域事件,頁面同時有多處請求時會互相干擾,正式環境建議改用區域變數控制 loading 的顯示。第二,伺服器回傳的內容最好經過白名單或型別驗證,避免把未過濾的內容直接寫回 DOM。第三,若欄位有格式限制(例如只能是數字),可在 blur 之前先做前端檢查,減少無效請求。