使用JQuery雙擊修改Table中Td

qingyezhu發表於2014-11-02
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <style>
        table{
            border-collapse:collapse;
            border-spacing:0;
            margin-right:auto;
            margin-left:auto;
            width:100%;
        }
        
        th,td{
            border:1px solid #b5d6e6;
            font-size:12px;
            font-weight:normal;
            vertical-align:middle;
            height:20px;
            width:25%;
        }
        th{
            text-align:center;
            background-color:Gray;
        }

    </style>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    $(function(){
$('#tableId').on('dblclick','td',function(){
                //console.info($(this).text());
                var oldVal = $(this).text();
                var input = "<input type='text' id='tmpId' value='" + oldVal + "' >";
                $(this).text('');
                $(this).append(input);
                $('#tmpId').focus();
                $('#tmpId').blur(function(){
                    if($(this).val() != ''){
                       oldVal = $(this).val();
                    }
                    //closest:是從當前元素開始,沿Dom樹向上遍歷直到找到已應用選擇器的一個匹配為止。
                   $(this).closest('td').text(oldVal);
                });
            });
});
</script>
</head>
<body>
<table id="tableId">
            <tr><th>head01</th><th>head02</th><th>head03</th><th>head04</th></tr>
            <tr><td>head11</td><td>head12</td><td>head13</td><td>head14</td></tr>
            <tr><td>head21</td><td>head22</td><td>head23</td><td>head24</td></tr>
            <tr><td>head31</td><td>head32</td><td>head33</td><td>head34</td></tr>
            <tr><td>head41</td><td>head42</td><td>head43</td><td>head44</td></tr>
        </table>
</body>
</html>

 

相關文章