Facebook 或現在一些 Web 2.0 網站流行讓文字即點即編輯的功能,
網上有已做好的 jQuery 庫可利用,或是如果你希望更了解其中奧秘,無妨親自動手做一個。
One of the most popular feature of the Web 2.0 sites such as Facebook is making it editable wherever you click. There are plenty of jQuery libraries on the internet. But you may create your own one, since you want to figure out the secret.

想要做成的效果:滑鼠點擊後,文字區域立刻變為可編輯區域,並多出一個送出結果的按鈕。
Now, I’d like to have a text span that will turn to editable once clicked, and a button for sending the data will appear.

HTML 的部分分為三塊去寫:
Remember to design your title span, text input area, and edit button.
1 2 3
| <span class="titleTxt" id="title_<?php echo $sn?>" title="<?php echo $title?>"><?php echo $ttitle?></span>
<input type="text" size="40" id="toTitle_<?php echo $sn?>" value="<?php echo $title?>" style="display:none;" />
<input type="button" class="editBtn" id="editBtn_<?php echo $sn?>" style="display:none;" value="修改" /> |
$sn 是序列號,$title 是標題文字。
未點擊 titleTxt 的 span 區域時,把 toTitle_? 和 editBtn_? 兩個元素隱藏起來。
$sn is serail number, and $title means title.
Hide your editable area and button when it has not been clicked.
然後在 jQuery 語法寫入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| $(".titleTxt").click(function(){
var this_ID=$(this).attr("id");
var idValue=this_ID.split('_');
var this_SN=idValue[1];
var this_toTitle="#toTitle_"+this_SN;
var this_BTN="#editBtn_"+this_SN;
$(this).empty(); //將 span 內清空,或是也可以用 hide()
$(this_toTitle).css('display',''); //顯示可編輯區域
$(this_BTN).css('display',''); //顯示按鈕
});
$(".editBtn").click(function(){
var this_ID=$(this).attr("id");
var idValue=this_ID.split('_');
var this_SN=idValue[1];
var input_toTitle="#toTitle_"+this_SN;
var this_toTitle=$(input_toTitle).val();
var this_BTN="#editBtn_"+this_SN;
var show_ID="#title_"+this_SN;
$.ajax({
type:"POST",
url: "ajax/comic_chapter_edit.php",
data: "title="+this_toTitle+"&sn="+this_SN,
success: function(response){
$(show_ID).empty().html(response); //把所得結果填入 span 內
$(input_toTitle).css('display','none'); //隱藏可編輯區域
$(this_BTN).css('display','none'); //隱藏按鈕
}
});
}); |
前端的部分這樣做就大功告成,最後記得將編輯標題的 php 程式寫入 ajax/comic_chapter_edit.php
並要 echo 出修改後的 title,以便前端順利接收到 response。
You should continue to write the php file "ajax/comic_chapter_edit.php", complete the programming.
Remember to echo the changed title in php, in order to send the response to the front end.