- 下面是项目的结构代码,需要拷贝使用注意引入要 jquery
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>全选</title>
<script src="./jquery-1.11.1.js"></script>
<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>
</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>
<tr>
<td>
<input type="checkbox" />
</td>
<td>jQuery</td>
<td>前端与移动开发学院</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<script>
$(function () {
$('#j_cbAll').click(function () {
var bool = $('#j_cbAll').prop('checked')
$('#j_tb input').prop('checked', bool)
})
$('#j_tb input').click(function () {
var n = $('#j_tb input:checked').length;
var m = $('#j_tb input').length;
var bool = (n === m)
$('#j_cbAll').prop('checked', bool)
})
})
</script>
- 总结: 像这种全选和单选按钮同步的问题的思路分成两个步骤
1. 就是将全选(input)按钮的(checked的属性)赋值变化赋值给那些单选按钮:全选按钮被选中状态,和其他单独按钮 被选中状态一致
2. 将单独按钮的数量和被选中的单独按钮的数量比较,得到一个布尔值,将这个布尔值赋值给全选按钮即可可达到单选按钮和全选按钮同步的效果