表格的增加和删除

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>表格删除和增加</title>
        <script type="text/javascript">

            var rowNum = 1;
            var colors = ["#FF0000","#00FF00","#0000FF","#FFFF00","#FF00FF","#00FFFF","#ABCDEF","#DEF123"];
            function addRow(){
                //创建三个文本结点
                var txtNode1 = document.createTextNode("单元格内容"+rowNum);
                var txtNode2 = document.createTextNode("单元格内容"+rowNum);
                var txtNode3 = document.createTextNode("单元格内容"+rowNum);

                //创建三个元素结点td
                var tdNode1 = document.createElement("td");
                var tdNode2 = document.createElement("td");
                var tdNode3 = document.createElement("td");

                //将三个文本结点依次添加到元素结点td中
                tdNode1.appendChild(txtNode1);
                tdNode2.appendChild(txtNode2);
                tdNode3.appendChild(txtNode3);

                //创建一个元素结点tr
                var trNode = document.createElement("tr");
                trNode.appendChild(tdNode1);
                trNode.appendChild(tdNode2);
                trNode.appendChild(tdNode3);

                var index = Math.floor(Math.random()*8);
                trNode.style.backgroundColor = colors[index];

                //将trNode添加到table中
                var tableNode = document.getElementById("tb");
                tableNode.appendChild(trNode);

                rowNum++;
            }
            function delRow(){
                var tableNode = document.getElementById("tb");
                tableNode.removeChild(tableNode.lastElementChild);

                rowNum--;
            }
        </script>
    </head>
    <body>
        <input type="button" value="新增一行" onclick="addRow();" />
        <input type="button" value="删除一行" onclick="delRow();" />
        <hr />
        <table id="tb" width="500" border="1">
            <!--
                <tr>
                    <td>单元格内容</td>
                    <td>单元格内容</td>
                    <td>单元格内容</td>
                </tr>   
            -->
        </table>
    </body>
</html>

这里写图片描述

posted @ 2018-05-29 15:45  hunterxing  阅读(227)  评论(0编辑  收藏  举报