时间:2021-01-18 编辑:
今天带来JavaScript实现简单动态表格教程详解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | < 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 > < 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 > < tbody >< tr > < th >编号</ th > < th >姓名</ th > < th >性别</ th > < th >操作</ th > </ tr > < tr > < td >1</ td > < td >武大郎</ td > < td >男</ td > < td >< a href = "javascript:void(0);" rel = "external nofollow" onclick = "delTr(this);" >删除</ a ></ td > </ tr > < tr > < td >2</ td > < td >西门庆</ td > < td >男</ td > < td >< a href = "javascript:void(0);" rel = "external nofollow" onclick = "delTr(this);" >删除</ a ></ td > </ tr > < tr > < td >3</ td > < td >武二郎</ td > < td >男</ td > < td >< a href = "javascript:void(0);" rel = "external nofollow" onclick = "delTr(this);" >删除</ a ></ td > </ tr > </ tbody ></ table > < script > //1.获取btn var btn_add = document.getElementById("btn_add"); //2.绑定单击事件 btn_add.onclick = function(){ //获取每一个输入框内容 var id = document.getElementById("id").value; var name = document.getElementById("name").value; var gender = document.getElementById("gender").value; //获取表格 var table = document.getElementById("table"); //创建tr var tr = document.createElement("tr"); //创建td var td_id = document.createElement("td"); var text_id = document.createTextNode(id); td_id.appendChild(text_id); tr.appendChild(td_id); var td_name = document.createElement("td"); var text_name = document.createTextNode(name); td_name.appendChild(text_name); tr.appendChild(td_name); var td_gender = document.createElement("td"); var text_gender = document.createTextNode(gender); td_gender.appendChild(text_gender); tr.appendChild(td_gender); var td_option = document.createElement("td"); var a = document.createElement("a"); a.setAttribute("href","javascript:void(0);"); a.setAttribute("onclick","delTr(this)"); var text_a = document.createTextNode("删除"); a.appendChild(text_a); td_option.appendChild(a); tr.appendChild(td_option); table.appendChild(tr); } function delTr(obj){ var table = obj.parentNode.parentNode.parentNode; var tr = obj.parentNode.parentNode; table.removeChild(tr); } </ script > |