Html动态表格

二次信任 提交于 2019-12-16 23:07:37
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动态表格</title>

    <style>
        table {
            border: 1px solid;
            margin: auto;
            width: 500px;
        }

        td, th {
            text-align: center;
            border: 1px solid;
        }

        div {
            text-align: center;
            margin: 50px;
        }
    </style>

</head>
<body>

<div>
    <input type="text" id="id" placeholder="请输入编号">
    <input type="text" id="name" placeholder="请输入姓名">
    <input type="text" id="gender" placeholder="请输入性别">
    <input type="button" value="添加" id="btn_add">

</div>


<table id="table">
    <caption>学生信息表</caption>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>操作</th>
    </tr>

    <tr>
        <td>1</td>
        <td>令狐冲</td>
        <td></td>
        <td><a href="javascript:void(0);" onclick="de(this);">删除</a></td>
    </tr>

    <tr>
        <td>2</td>
        <td>任我行</td>
        <td></td>
        <td><a href="javascript:void(0);"onclick="de(this);">删除</a></td>
    </tr>

    <tr>
        <td>3</td>
        <td>岳不群</td>
        <td>?</td>
        <td><a href="javascript:void(0);"onclick="de(this);">删除</a></td>
    </tr>


</table>
<script>
    function $(id) {
        return document.getElementById(id);
    }

    function c(s) {
        return document.createElement(s);
    }

    var table = $("table");

    function add() {
        var id = $("id").value;
        var name = $("name").value;
        var gender = $("gender").value;
        var btn_add = $("btn_add").value;

        var tr = c("tr");
        tr.setAttribute("id", "tr");
        table.appendChild(tr);
        var td_id = c("td");
        td_id.setAttribute("id", "td_id");
        tr.appendChild(td_id);
        td_id.appendChild(document.createTextNode(id));

        var td_name = c("td");
        td_name.setAttribute("id", "td_name");
        tr.appendChild(td_name);
        td_name.appendChild(document.createTextNode(name));

        var td_gender = c("td");
        td_gender.setAttribute("id", "td_gender");
        tr.appendChild(td_gender);

        td_gender.appendChild(document.createTextNode(gender));

        var td_btn_add = c("td");
        td_btn_add.setAttribute("id", "td_btn_add");
        tr.appendChild(td_btn_add);
        var a = c("a");
        a.setAttribute("id","a");
        a.setAttribute("href","javascript:void(0);");
        a.setAttribute("onclick","de(this);")
        a.appendChild(document.createTextNode("删除"));
        td_btn_add.appendChild(a);
    }
    function de(e){
        e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
    }

    $("btn_add").onclick = add;
</script>
</body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!