jQuery全选,全不选
演示效果:
jQuery全选,全不选
HTML代码
<div class="books">
<h3 class="titl">图书管理</h3>
<table cellspacing="0" cellpadding="0">
<thead>
<tr>
<th><input type="checkbox" id="all" /></th>
<th>作者</th>
<th>作品</th>
</tr>
</thead>
<tbody id="list">
<tr>
<td><input type="checkbox"/></td>
<td>三毛</td>
<td>《说给自己听》</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>张嘉佳</td>
<td>《从你的全世界路过》</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>张嘉佳</td>
<td>《云边有个小卖部》</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>余华</td>
<td>《活着》</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>李诞</td>
<td>《笑场》</td>
</tr>
</tbody>
</table>
</div>
css片段:
border-collapse: collapse;加在table里面否则tr的边框不生效
/* jQuery全选 */
.books{width: 500px;margin: 200px auto 0;box-sizing: border-box;}
.books .titl{font-size: 30px;color: #09c;text-align: center;margin-bottom: 30px;box-sizing: border-box;}
.books table{border: 1px solid #DDDDDD;width: 100%;border-collapse: collapse;}
.books table thead{width: 100%;background-color: #09c;}
.books table thead th{border-right: 1px solid #DDDDDD;height: 50px;font-size: 16px;color: #FFFFFF;}
.books table thead th:last-child{border: none;}
.books table tbody{width: 100%;}
.books table tbody tr{width: 100%;height: 40px;border-bottom: 1px solid #DDDDDD;}
.books table tbody tr td{border-right: 1px solid #DDDDDD;text-align: center;}
.books table tbody tr:nth-of-type(even){background-color: #EEEEEE;}
jQuery片段:
注意:一定要先引入jQuery
$(function(){
// 全选
$("#all").click(function(){
var all=$(this).prop("checked");//获取全选按钮状态
$("#list input").prop("checked",all);//将或取到的状态添加给#list下面input
console.log(all)
})
//通过list下的input改变all属性值
$("#list input").click(function(){
var allLength=$("#list input").length;//获取所有input数量
var djLength=$("#list input:checked").length;//获取点击后的input数量
if(djLength==allLength){//判断点击量是否等于总数量
$("#all").prop("checked",true);//是,全选
}else{
$("#all").prop("checked",false);//否,取消全选
}
})
})