<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <!--4、编号:文本框 书名:文本框 作者:文本框 出版社:文本框 添加按钮 表格 编号 书名 作者 出版社 删除--> </head> <body> <div id="all"> <p>编 号:<input type="text"></p> <p>书 名:<input type="text"></p> <p>作 者:<input type="text"></p> <p>出版社 :<input type="text"></p> <p> <input type="button" value="添加" id="tj"> <input type="button" value="清除" id="cle"> </p> </div> <script> var ins, tj, qc, tab, all; var bookData = ["编号", "书名", "作者", "出版社", "删除"]; init(); function init() { all = document.getElementById("all"); ins = document.getElementsByClassName("in"); tj = document.getElementById("tj"); qc = document.getElementById("cle"); del = document.getElementById("del"); tj.addEventListener("click", clickHandler); qc.addEventListener("click", clickQcHandler); creatTable(); } function creatTable() { tab = $c("table", all, { "500px", borderCollapse: "collapse" }); for(var i = 0; i < ins.length + 1; i++) { //购物车表单数据赋值 var th = $c("th", tab, { textAlign: "center", border: "1px solid #000000" }); th.textContent = bookData[i]; } } function clickHandler() { var tr = $c("tr", tab, { textAlign: "center", border: "1px solid #000000" }); for(var i = 0; i < ins.length + 1; i++) { //购物车表单数据赋值 var td = $c("td", tr, { //列的创建 textAlign: "center", border: "1px solid #000000" }); if(i < ins.length) { td.textContent = ins[i].value; } else if(i == ins.length) { var del = $c("button", td); del.textContent = "删除"; del.addEventListener("click", clickDelHandler); } } } function clickDelHandler(e) { //删除 一行 this.parentNode.parentNode.remove(); } function clickQcHandler(e) { //清除 全部 tab.remove(); creatTable(); } function $c(type, parent, style) { var elem = document.createElement(type); if(parent) parent.appendChild(elem); for(var key in style) { elem.style[key] = style[key]; } return elem; } </script> </body> </html>