使用DOM操作表格
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
#table{
text-align: center;
}
</style>
<script>
//新增新行
function addNewTr(){
var lastRow = document.getElementById("lastRow");
var newTr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var td4 = document.createElement("td");
td1.innerHTML = "103";
td2.innerHTML = "詹姆斯";
td3.innerHTML = "25897456";
td4.innerHTML = "547883";
//把td新增到tr中
newTr.appendChild(td1);
newTr.appendChild(td2);
newTr.appendChild(td3);
newTr.appendChild(td4);
if(confirm("是否新增新行?")){
lastRow.parentNode.appendChild(newTr);
}
//或者 document.getElementById("tbody").appendChild(newTr);
}
//複製表頭行
function copyHeadTr(){
var thead = document.getElementById("thead");
var copyThead = thead.cloneNode(true);
if(confirm("是否新增?")){
thead.parentNode.appendChild(copyThead);
}
}
//刪除資料首行
function deleFirstTr(){
var tbody = document.getElementById("firstTr");
if(confirm("刪除嗎?")){
tbody.parentNode.removeChild(tbody);
}
}
</script>
</head>
<body>
<table border="1" width="500" id="table">
<thead>
<tr id="thead">
<td>編號</td>
<td>姓名</td>
<td>電話號碼</td>
<td>月薪(元)</td>
</tr>
</thead>
<tbody id="tbody">
<tr id="firstTr">
<td>100</td>
<td>庫裡</td>
<td>125478</td>
<td>25410</td>
</tr>
<tr>
<td>101</td>
<td>科比</td>
<td>1478954</td>
<td>111111</td>
</tr>
<tr id="lastRow">
<td>102</td>
<td>圖藍天</td>
<td>4789512</td>
<td>245845</td>
</tr>
</tbody>
</table>
<br />
<input type="button" value="新增新行" onclick="addNewTr()"/>
<input type="button" value="複製表頭行" onclick="copyHeadTr()" />
<input type="button" value="刪除資料首行" onclick="deleFirstTr()"/>
</body>
</html>