jQuery下table操作示例(附案例源码)

2022-11-29 17:54:09 浏览数 (1)

练习效果:(仅用于技术点练习

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
    <script>
        //删除
        function del(o) {
            $(o).parent().parent().remove();
        }
        //修改
        function update(o) {
            if ($(o).text() == "修改") {
                $(o).text("保存");
                var c = $(o).parent().prevAll();
                var chang = $(o).parent().prevAll().length;
                for (var i = 0; i < chang; i  ) {
                    var text = c[i].textContent;
                    c[i].innerHTML = "<input type='text' value='"   text   "'/>";
                }
            } else if ($(o).text() == "保存") {
                $(o).text("修改");
                var c = $(o).parent().prevAll();
                var chang = $(o).parent().prevAll().length;
                for (var i = 0; i < chang; i  ) {
                    c[i].innerHTML = $(c[i]).children().val();
                }
            }
        }
        //添加
        function add() {
            //复制元素clone
            var c = $("tr:eq(1)").clone();
            //添加到table的最后
            c.appendTo($("table"));
        }
        //查询
        function find() {
            //需要查询的内容
            var cha = $("#cha").val();
            if (cha != "") {
                var result = "";
                var list = $("tr:gt(0)");
                for (var i = 0; i < list.length; i  ) {
                    if ($(list[i]).children()[0].textContent == cha) {
                        result = $(list[i]).clone();
                    }
                }
                if (result != "") {
                    $("tr:gt(0)").hide();
                    result.appendTo($("table"));
                }
            } else {
                window.location.reload();
            }
        }
    </script>
</head>

<body>
    <a href="#" onclick="add()">添加</a>
    <input type="text" id="cha" /><a href="#" onclick="find()">查询</a>
    <table border="1">
        <tr>
            <td>编号</td>
            <td>姓名</td>
            <td>薪水</td>
            <td>功能</td>
        </tr>
        <tr>
            <td>1</td>
            <td>李宁</td>
            <td>10000</td>
            <td>
                <a href="#" onclick="update(this)">修改</a>
                <a href="#" onclick="del(this)">删除</a>
            </td>
        </tr>
        <tr>
            <td>2</td>
            <td>小灰灰</td>
            <td>12000</td>
            <td>
                <a href="#" onclick="update(this)">修改</a>
                <a href="#" onclick="del(this)">删除</a>
            </td>
        </tr>

    </table>
</body>

</html>

希望能对大家有所帮助。

0 人点赞