<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.info{
width: 900px;
min-height: 300px;
border: 1px solid red;
margin: 50px auto;
}
.info .up{
height: 50px;
display: flex;
align-items: center;
justify-content: space-between;
}
.info .up input{
height: 25px;
border: 1px solid #ccc;
outline: none;
}
.info .up input:last-child{
width: 100px;
box-sizing: content-box;
cursor: pointer;
}
.info table{
width: 100%;
border: 1px solid red;
text-align: center;
}
.info table thead tr th{
border: 1px solid red;
height: 30px;
}
.info table tbody tr td{
border: 1px solid red;
}
.info table tbody tr td span{
cursor: pointer;
}
</style>
</head>
<body>
<div class="info">
<div class="up">
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="button" value="添加" />
</div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>专业</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td><span>删除</span></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td><span>删除</span></td>
</tr> -->
</tbody>
</table>
</div>
<script>
var sum=0
var input=document.querySelectorAll('input')
var inputs=document.querySelector('input[type=button]')
var tbody=document.querySelector('tbody')
inputs.οnclick=function(){
for(var i=0;i<input.length;i++){
if(input[i].value.trim()==''){
return alert('不能有空的输入内容')
}
}
var tr= document.createElement('tr')
tbody.appendChild(tr)
var tr=document.querySelectorAll('tbody>tr')[sum]
sum++
for(var i=0;i<input.length-1;i++){
var td= document.createElement('td')
tr.appendChild(td)
td.innerHTML=input[i].value
}
var td= document.createElement('td')
tr.appendChild(td)
td.innerHTML='<span>删除</span>'
var span=document.querySelectorAll('span')
for(var i=0;i<span.length;i++){
span[i].οnclick=function(){
this.parentNode.parentNode.remove()
}
}
}
</script>
</body>
</html>
js表格添加和删除内容
于 2023-12-06 19:29:11 首次发布