效果图:
<!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>
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
border: 1px solid #aaa;
text-align: center;
}
</style>
</head>
<body>
<h2>学生信息管理</h2>
<div class="students_info">
<input type="text" placeholder="请输入学生姓名" class="students_name">
<br>
<input type="text" placeholder="请输入学生年龄" class="students_age">
<br>
<div class="sexBox">
<input type="radio" name="sex" class="sex" value="男">男
<input type="radio" name="sex" class="sex" value="女">女
</div>
<br>
<button class="add">添加</button>
<hr>
</div>
<table class="students">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
<script>
var students_name = document.querySelector('.students_name')
var students_age = document.querySelector('.students_age')
var sex = document.querySelectorAll('.sex ')
var sexBox = document.querySelector('.sexBox')
var tbody = document.querySelector('tbody')
var sexValue = ''
var add = document.querySelector('.add')
add.onclick = function() {
let nameValue = students_name.value
let ageValue = students_age.value
if (nameValue && ageValue && sexValue) {
let tr = document.createElement('tr')
tr.innerHTML = `<td>${nameValue}</td>
<td>${ageValue}</td>
<td>${sexValue}</td>
<td><button class="remove">删除</button></td> `
tbody.appendChild(tr)
students_name.value = ""
students_age.value = ""
} else {
alert('请输入完整的学生信息')
}
}
tbody.onclick = function(e) {
if (e.target.tagName == 'BUTTON') {
let result = confirm('确定要删除此学生信息吗?')
if (result) {
let tr = e.target.parentNode.parentNode
tr.parentNode.removeChild(tr)
}
}
}
sexBox.onchange = function(e) {
if (e.target.type == 'radio') {
for (let i = 0; i < sex.length; i++) {
if (sex[i].checked) {
sexValue = sex[i].value
}
}
}
}
</script>
</html>