點擊table中的td,修改td中的內容功能實現

<h2>點擊table中的td,修改td中的內容</h2> <p>前段時間,需要搭建演示頁面,有個功能是實現點擊表格中的某一格,能夠修改對應格子中的內容,一開始不知道怎麼寫,在網上找了一下,自己再整合了一下,功能實現的代碼如下。</p>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <title>Title</title>
</head>
<body>


<table border="1" class="setRecordStatus">
    <tr>
        <th>設備ID</th>
        <th>設備通道號</th>
        <th>實時播放地址</th>
    </tr>
    <tbody >
    <tr >
        <td class="deviceInfo">000001</td>
        <td class="deviceInfo">000001</td>
        <td class="deviceInfo">rtsp://192.168.1.2:554/stream1</td>
    </tr>
    </tbody>
</table>

<style type="text/css">
    /**
     *  把表格固定住,td長度固定,td中溢出的內容用...來代替
     * */
    table{
        width: 600px;
        table-layout:fixed;
    }
    td{
        height: 30px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
</style>

<script type="text/javascript">
    changeTableTd();
    /**
     *
     * 添加鼠標點擊事件,可以改變table中表格的值
     * */
    function changeTableTd(){
        // 獲取所有的單元格
        td = document.getElementsByClassName("deviceInfo");
        $(function () {
            $(".deviceInfo").click(function () {
                var index = $(this).index();
                $(".setRecordStatus tr td").eq(index).html("");
                var input = document.createElement("input");
                input.type = "text";
                input.style.width = "100%";
                this.innerHTML = "";
                this.appendChild(input);
                input.focus();
                input.onblur = function () {
                    $(".setRecordStatus tr td").eq(index).html(input.value);
                    console.log("輸入的值是" +input.value);
                    input.remove();
                };
            })
            ;
        });
    };
</script>


</body>
</html>

###原始表格

###點擊過後的表格

###Tips 直接導入cdn的jquery的庫,所以代碼賦值粘貼下來可以直接進行功能展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章