点击table中的td,修改td中的内容功能实现

点击table中的td,修改td中的内容

前段时间,需要搭建演示页面,有个功能是实现点击表格中的某一格,能够修改对应格子中的内容,一开始不知道怎么写,在网上找了一下,自己再整合了一下,功能实现的代码如下。

<!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的库,所以代码赋值粘贴下来可以直接进行功能展示。


真正项目中,最好还是从本地调用jquery的库。

猜你喜欢

转载自www.cnblogs.com/dad-world/p/12214659.html