JS动态创建html table与删除table row

首次发布:2017-09-17 22:59


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <style>
    </style>
    <script type="text/javascript">
        function btnDelete(row1) {
            var tr = row1.parentNode.parentNode;
            document.getElementById('tbd1').removeChild(tr);
        }
        window.onload = function () {
            var txt1 = document.getElementById('txt1');
            var txt2 = document.getElementById('txt2');
            document.getElementById('btn1').onclick = function () {
                var tbdy = document.getElementById('tbd1');
                var trow = tbdy.insertRow(-1);
                trow.insertCell(-1).innerHTML = txt1.value;
                trow.insertCell(-1).innerHTML = txt2.value;

                var cell1 = trow.insertCell(-1);
                cell1.align = 'center';
                cell1.innerHTML = '<input type="button" value="删除" onclick="btnDelete(this);" />';               
            }
        }
    </script>
</head>
<body>
    <fieldset style="width:230px;">
        <legend>添加信员信息</legend>
        <p>姓名:<input type="text" id="txt1" /></p>
        <p>年龄:<input type="text" id="txt2" /></p>
        <p><input type="button" value="添加" id="btn1" /></p>
    </fieldset>

    <table border="1" width="230" cellspacing="1" style="background-color:#f0f0f0" id="tb1">
        <caption>人员信息</caption>
        <thead>
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>删除</th>
            </tr>
        </thead>
        <tbody id="tbd1"></tbody>
    </table>
</body>
</html>