JavaScript實現簡單動態表格
阿新 • • 發佈:2020-12-03
本文例項為大家分享了JavaScript實現簡單動態表格的具體程式碼,供大家參考,具體內容如下
程式碼:
<!DOCTYPE html> <html lang="en"> <head> <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> </head> <body> <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> <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" rel="external nofollow" 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" rel="external nofollow" 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" rel="external nofollow" rel="external nofollow" onclick="delTr(this);">刪除</a></td> </tr> </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> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。