前台特效(3) 编辑表格

<!DOCTYPE html>
<html>
    <head>
        <title>编辑表格</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script>
        <script>
            $(function(){
                var off = true;
                $("#table td").each(function(){
                    $(this).click(function(){
                        if(off){
                            var cont = $(this).html();
                            $(this).html('');
                            $(this).append("<input type='text' id='cont' value='"+cont+"'/>");
                            $("#cont").focus().css("background-color","#ffffcc");
                            off = false;
                        }
                    })
                });
                $("#cont").live({blur:function(){
                        $(this).parent().html($(this).val());
                        off = true;
                    },keydown:function(event){
                        if(event.keyCode == 13){
                            $(this).parent().html($(this).val());
                            off = true; 
                        }
                    }});
            })
        </script>
        <style>
            #table{
                border: solid 3px #cccccc;
                text-align: center;
                padding: 5px;
            }
            #table td{
                width:200px;
                height:30px;
                border: solid 3px #cccccc;
            }
        </style>
    </head>
    <body>
        <table id="table">
            <tr>
                <td>11</td>
                <td>12</td>
                <td>13</td>
                <td>14</td>
                <td>15</td>
            </tr>
            <tr>
                <td>21</td>
                <td>22</td>
                <td>23</td>
                <td>24</td>
                <td>25</td>
            </tr>
            <tr>
                <td>31</td>
                <td>32</td>
                <td>33</td>
                <td>34</td>
                <td>35</td>
            </tr>
            <tr>
                <td>41</td>
                <td>42</td>
                <td>43</td>
                <td>44</td>
                <td>45</td>
            </tr>
        </table>
    </body>
</html>

基本思路:

1.点击table的td时触发click时间,获取td内容并赋予新添加的input,删除td的内容,添加input

2.点击同时,使input获取焦点并改变背景颜色

3.当input失去焦点或者按下Enter键时,获取input的value,覆盖到td

希望对你有所帮助! ^_^~

原文地址:https://www.cnblogs.com/longdidi/p/2952493.html