CSS部分
<style>
#form {
width: 480px;
margin: 30px auto;
border: 1px solid #eee;
border-radius: 5px;
padding: 10px;
line-height: 30px;
position: relative;
}
button {
position: absolute;
right: 10px;
bottom: 10px;
}
#tab {
width: 500px;
margin: 30px auto;
border-collapse: collapse;
}
th,
td {
border: 1px solid #000;
padding: 5px;
}
tbody tr td:first-child {
text-align: center;
}
/*input[type] 属性选择器 选择input标签,并且有type属性input标签*/
/*input[type = "checkbox"] 选择有type属性并且值为checkbox的input标签*/
input[type="checkbox"] {
width: 15px;
height: 15px;
}
#div1 {
position: relative;
width: 480px;
padding: 10px;
margin: 0 auto;
}
</style>
HTML部分
<div id="form">
请输入姓名: <input type="text" id="name"> <br> 请输入性别: <input type="radio" id="sex" name="sex" checked value="男"> 男<input type="radio" name="sex" value="女">女<br> 请输入年龄: <input type="text" id="age">
<button>添加到表格</button>
</div>
<table id="tab">
<thead>
<tr>
<th width="20%"><input type="checkbox" id="all">全选</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>张三</td>
<td>女</td>
<td>88</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>李四</td>
<td>男</td>
<td>18</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>王五</td>
<td>女</td>
<td>1</td>
</tr>
</tbody>
</table>
<div id="div1">
<button>删除所选行</button>
</div>
JQ部分
<script>
$(document).ready(function() {
// 全选/全不选复选框
$("#all").click(function() {
var isChecked = $(this).prop('checked');
$('input[type="checkbox"]').each(function() {
if ($(this).is(":not(#all)") && !$(this).is(':disabled')) {
$(this).prop('checked', isChecked);
}
});
});
// 行复选框点击事件处理程序
$("table tbody").on('click', 'input[type="checkbox"]', function() {
var allChecked = ($('input[type="checkbox"]:not(#all)').length === $('input[type="checkbox"]:not(#all):checked').length);
$("#all").prop('checked', allChecked);
});
// 删除所选行
$("#div1 button").click(function() {
$("table tbody").find('input[type="checkbox"]:checked').closest("tr").remove();
});
// 添加到表格按钮点击事件处理程序
$("#form button").click(function() {
var name = $("#name").val();
var sex = $("input[name='sex']:checked").val();
var age = $("#age").val();
if (name && sex && age) {
var newRow = "<tr><td><input type='checkbox'></td><td>" + name + "</td><td>" + sex + "</td><td>" + age + "</td></tr>";
$("table tbody").append(newRow);
// 清空输入框
$("#name").val("");
$("#age").val("");
$("input[name='sex']").prop("checked", false);
// 更新全选复选框状态
var allChecked = ($('input[type="checkbox"]:not(#all)').length === $('input[type="checkbox"]:not(#all):checked').length);
$("#all").prop('checked', allChecked);
} else {
alert("请填写完整的信息!");
}
});
// 删除所选行按钮点击事件处理程序
$("#div1 button").click(function() {
var checkboxes = $("table tbody").find('input[type="checkbox"]:checked');
if (checkboxes.length >= 0) {
checkboxes.closest("tr").remove();
$("#all").prop("checked", false);
} else {
alert("请先选择要删除的行!");
}
});
});
</script>