DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
點擊文字變輸入框、存檔後再變回文字的互動實作
編輯:HTML和Xhtml     

「點一下變成輸入框、編輯完按儲存又變回文字」是很常見的表格就地編輯(inline edit)互動,能讓使用者不必跳頁就能修改資料。以下用 jQuery 實作這個效果。

HTML 結構

用一個表格呈現品項與數量,可編輯的儲存格加上 edit 類別,底部放一顆切換用按鈕:

<table>
<thead>
<tr>
    <th width="400">品名</th>
    <th width="200">件數</th>
</tr>
</thead>
<tbody>
<tr height="50">
    <td>iPhone6s</td>
    <td class="edit">2</td>
</tr>
<tr height="50">
    <td>小米5</td>
    <td class="edit">5</td>
</tr>
</tbody>
<tfoot>
<tr>
    <td colspan="2" class="text-right">
        <button type="button" onclick="change(this)">修改</button>
    </td>
</tr>
</tfoot>
</table>

切換邏輯

JavaScript 依按鈕目前的文字判斷狀態:若為「修改」,就把每個可編輯儲存格的內容換成輸入框並填入原值;若為「保存」,則把輸入框的值寫回儲存格並還原成純文字:

function change(obj){
    var xg = $(obj).html();
    if (xg == '修改') {
        $('.edit').each(function(){
            var old = $(this).html();
            $(this).html("<input type='text' class='text' value=" + old + ">");
        });
        $(obj).html('保存');
    } else if (xg == '保存') {
        $('input').each(function(){
            var newfont = $(this).val();
            $(this).parent('td').html(newfont);
        });
        $(obj).html('修改');
    }
}

如此一來,同一顆按鈕就能在「修改」與「保存」兩種狀態間靈活切換,讓表格編輯變得直覺又順手。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved