您的位置:首页 > Web前端 > JQuery

用jQuery实现复选框的全选、全不选、和反选

2016-02-15 15:22 741 查看
用一个例子来说明一下,html页面代码如下

<table border="1" align="center">
<thead>
<tr>
<th>状态</th>
<th>用户名</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /></td>
<td>赵</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>钱</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>孙</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>李</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>周</td>
</tr>
</tbody>
<tfoot>
<tr>
<td><input type="checkbox" /> 全选</td>
<td><input type="button" value="全反选" /></td>
</tr>
</tfoot>
</table>


在浏览器中的效果是这样的:



要实现单击“全选”前面的那个复选框实现全选和全不选的切换,我用的jQuery版本是1.12.0,刚开始的思路是这样的:

$("tfoot tr input:first").click(function(){
if($(this).is(":checked")){ //判断复选框是否被选中
$("table :checkbox").attr("checked","checked");
}
else{
$("table :checkbox").removeAttr("checked");
}
});


这么写的话全选只能执行一次,什么意思呢,截图更明白些


(第一次“全选”有效),

(第一次“全不选”也有效),

(第二次“全选”就无效了)

这是因为移除checked属性时浏览器产生了错误。所以以上的这种方法不适用。

以下这种方法是有效的:

$("tfoot tr input:first").click(function(){
if($(this).is(":checked")){
$("table :checkbox").prop("checked",true);
}
else{
$("table :checkbox").prop("checked",false);
}
});


这里用了prop方法来设置属性。

接下来“反选”也可以用prop这个方法来做:

$("tfoot tr input:last").click(function(){
$("table :checkbox").each(function(){
if($(this).is(":checked")==false){
$(this).prop("checked",true);
}
else{
$(this).prop("checked",false);
}
});
});


当然,这个例子还有很多不完善的的地方,这里主要是说明我遇到的主要的问题,其余的情况就不在这里讨论了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: