jQuery学习 (表单全选与反选功能)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 300px;
margin: 100px auto 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
}
th,
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
<script src="jquery-3.3.1.js"></script>
<script>
$(function () {
//为全选的复选框添加点击的方法
$("#j_cbAll").click(function () {
//当前的复选框选中
//结果:true或者false
var checked = $("#j_cbAll").prop("checked");
$("#j_tb").find(":checkbox").prop("checked", checked);
//$("input[type='checkbox']").prop("checked",checked);
});
//为tbody中所有的checkbox添加点击的方法
$("#j_tb").find(":checkbox").click(function () {
//获取所有的checkbox的个数
var checkboxLength=$("#j_tb").find(":checkbox").length;
//获取所有选中的checkbox的个数
var checkedLength=$("#j_tb").find(":checked").length; //核心代码伪元素的选择方式 .find(":checked")
//判断个数是否相等
if(checkboxLength==checkedLength){
$("#j_cbAll").prop("checked",true);
}else{
$("#j_cbAll").prop("checked",false);
}
});
});
</script>
</head>
<body>
<div class="wrap">
<table>
<thead>
<tr>
<th>
<input type="checkbox" id="j_cbAll" />
</th>
<th>课程名称</th>
<th>所属学院</th>
</tr>
</thead>
<tbody id="j_tb">
<tr>
<td>
<input type="checkbox" />
</td>
<td>JavaScript</td>
<td>前端与移动开发学院</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>css</td>
<td>前端与移动开发学院</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>html</td>
<td>前端与移动开发学院</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
坚持

浙公网安备 33010602011771号