JavaScript实现动态表格的创建

来源:互联网 发布:吕鑫讲的c语言咋样 编辑:程序博客网 时间:2024/06/10 10:12

全部实现表格的动态创建。
要求:表格表头内容为”编号,学号,姓名,年龄,手机号,操作”,
操作列包括两个按钮【添加】【删除】可以动态为这个表格添加行,也可以删除行。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>实现动态表格的设计</title></head><body><button id="button1" onclick="addRows()">添加</button><button id="button2" onclick="deleteRows()">删除</button><script type="text/javascript">    //1.创建表格    var table=document.createElement("table");    table.border="1";    table.width="800px";    //2.创建tbody    var tb=document.createElement("tbody");    table.appendChild(tb);    //3.创建表头    var tr1=document.createElement("tr");    tb.appendChild(tr1);    var th1=document.createElement("th");    th1.appendChild(document.createTextNode("编号"));    tr1.appendChild(th1);    var th2=document.createElement("th");    th2.appendChild(document.createTextNode("学号"));    tr1.appendChild(th2);    var th3=document.createElement("th");    th3.appendChild(document.createTextNode("姓名"));    tr1.appendChild(th3);    var th4=document.createElement("th");    th4.appendChild(document.createTextNode("年龄"));    tr1.appendChild(th4);    var th5=document.createElement("th");    th5.appendChild(document.createTextNode("手机号"));    tr1.appendChild(th5);    var th6=document.createElement("th");    th6.appendChild(document.createTextNode("操作"));    tr1.appendChild(th6);    tb.insertRow(1);    tb.rows[1].insertCell(0);                            tb.rows[1].cells[0].appendChild(document.createTextNode("1,1"));    tb.rows[1].insertCell(1);    tb.rows[1].cells[1].appendChild(document.createTextNode("1,1"));    tb.rows[1].insertCell(2);    tb.rows[1].cells[2].appendChild(document.createTextNode("1,1"));    tb.rows[1].insertCell(3);    tb.rows[1].cells[3].appendChild(document.createTextNode("1,1"));    tb.rows[1].insertCell(4);    tb.rows[1].cells[4].appendChild(document.createTextNode("1,1"));    tb.rows[1].insertCell(5);    tb.rows[1].cells[5].appendChild(document.getElementById("button1"));    tb.rows[1].cells[5].appendChild(document.getElementById("button2"));    document.body.appendChild(table);    function addRows(){        tb.insertRow(1);               tb.rows[1].insertCell(0).appendChild(document.createTextNode("new cell"));        tb.rows[1].insertCell(1).appendChild(document.createTextNode("new cell"));        tb.rows[1].insertCell(2).appendChild(document.createTextNode("new cell"));        tb.rows[1].insertCell(3).appendChild(document.createTextNode("new cell"));        tb.rows[1].insertCell(4).appendChild(document.createTextNode("new cell"));        tb.rows[1].insertCell(5).appendChild(document.createTextNode("new cell"));    }    function deleteRows(){        tb.deleteRow(1);    }</script></body></html>