代码(第一种):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.first{
width: 1000px;
border: 1px solid #ddd;
border-radius: 10px;
padding:20px;
margin: 10px auto;
}
.first input{
font-size: 14px;
color:#444;
padding:5px;
}
.list{
width:800px;
margin:10px auto;
}
.list table{
width:100%;
border-collapse: collapse;
border:1px solid #ccc;
font-size: 16px;
line-height: 16px;
color:#444;
}
.list th,.list td{
border:1px solid #ccc;
padding:10px;
text-align: center;
}
.list table a{
text-decoration: none;
color:red;
}
.list thead{
background-color: #369;
}
</style>
<script src="jquery1.7.2.js"></script>
<script>
$(function() {
$('#add').click(function(){
var $number=$('#number').val();
var $name=$('#name').val();
var $stuID=$('#stuID').val();
var $sex=$("#man:checked").val() ? '男':'女';
if($number !=''&& $name!='' && $stuID!='')
{
$('table tbody').append("<tr><td>" + $number +"</td><td>" + $name +"</td><td>"+$stuID+ "</td><td>"+ $sex +"</td> <td><a href='javascript:void(0);'>删除</a></td>")
$('#number').val('');
$('#name').val('');
$('#stuID').val('');
}
else{
alert("请输入全部内容");
}
del();
});
function del(){
$('a').click(function(){
$(this).parents('tr').remove();
})
}
del();
})
</script>
</head>
<body>
<div class="first">
<label for="number">序号:
<input type="text" id="number">
</label>
<label for="name">姓名:
<input type="text" id="name">
</label>
<label for="stuID">学号:
<input type="text" id="stuID">
</label>
<label for="">性别:
<label for="man">男:
<input type="radio" id="man" checked="checked" name="sex">
</label>
<label for="woman">女:
<input type="radio" id="woman" name="sex">
</label>
</label>
<input type="button" id="add" value="添加">
</div>
<div class="list">
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>学号</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>01</td>
<td>燕高远</td>
<td>184804056</td>
<td>男</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
效果:
实现步骤:
1.找到“添钮”按钮的id,设置点击事件
2.点击事件中,获取表单元素中的值(序号,姓名,学号,性别)
3.判断输入框是否为空,为空不能添加
4.如果不为空,在table中tbody追加内容,追加单元格以及删除的标签
4.添加完成后,清空文本框内容
5.写一个删除函数,点击a标签,移除a标签的父标签(移除a标签所在的一行)