本文实例为大家分享了JavaScript实现动态表格效果的具体代码,供大家参考,具体内容如下
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态表格</title>
<style>
.bigDiv{
width: 600px;
margin: 50px auto;
}
table{
border: solid black 2px;
width: 500px;
border-collapse: collapse;
}
th{
background-color: darkgray;
font-weight: bold;
color: #ffffff;
}
th,td{
border: 1px solid black ;
box-sizing: content-box;
text-align: center;
width: 50px;
height: 30px;
font-size: 14px;
}
.but{
width: 150px;
margin: 5px 400px;
display: flex;
justify-content: flex-end;
}
</style>
</head>
<body>
<div class="bigDiv">
<table align="center">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>联系电话</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>逍遥</td>
<td>18</td>
<td>男</td>
<td>12354546</td>
</tr>
<tr>
<td>2</td>
<td>小白</td>
<td>19</td>
<td>女</td>
<td>252323523</td>
</tr>
</tbody>
</table>
<div class="but">
<button type="button" onclick="addRow()">添加一行</button>
<button type="button" onclick="saveData()">保存数据</button>
</div>
</div>
<script>
var id;
var name;
var age;
var sex;
var phone;
var tdArr=new Array();
function addRow() {
let tbodyObj = document.getElementsByTagName("tbody")[0];
let trObj = document.createElement("tr");
tbodyObj.appendChild(trObj);
//创建5个td
for (let i = 0; i < 5; i++) {
let tdObj = document.createElement("td");
trObj.appendChild(tdObj);
//创建input输入框对象
let inputObj = document.createElement("input");
//设置input对象的id属性
inputObj.setAttribute("id",i);
//为每一个输入框添加一个失去焦点事件
inputObj.addEventListener("blur",function () {
switch (this.id) {
case "0":
id=this.value;
break;
case "1":
name=this.value;
break;
case "2":
age=this.value;
break;
case "3":
sex=this.value;
break;
case "4":
phone=this.value;
break;
}
});
//隐藏未点击输入时的input边框
inputObj.style.border="0";
//隐藏点击输入时的边框
inputObj.style.outline="none";
//设置输入框宽度
inputObj.style.width="80px";
//设置输入框高度
inputObj.style.height="25px";
//设置输入框的外边距为0
inputObj.style.margin="0";
//将td添加
tdObj.appendChild(inputObj);
//将tdObj添加到tdArr中
tdArr.push(tdObj);
}
}
function saveData() {
tdArr[0].innerHTML=id;
tdArr[1].innerHTML=name;
tdArr[2].innerHTML=age;
tdArr[3].innerHTML=sex;
tdArr[4].innerHTML=phone;
tdArr.length=0;
}
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。