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

本文介绍使用jQuery实现HTML表格中全选与全反选功能的方法。通过点击“全选”按钮,可以实现所有复选框的选择状态切换;点击“全反选”按钮,则反转所有复选框的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用一个例子来说明一下,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);
                }
            });
        });

当然,这个例子还有很多不完善的的地方,这里主要是说明我遇到的主要的问题,其余的情况就不在这里讨论了。

转载于:https://www.cnblogs.com/feixiang92/p/5190595.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值