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

用一个例子来说明一下,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张图片

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

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

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

用jQuery实现复选框的全选、全不选、和反选_第2张图片(第一次“全选”有效),用jQuery实现复选框的全选、全不选、和反选_第3张图片(第一次“全不选”也有效),用jQuery实现复选框的全选、全不选、和反选_第4张图片(第二次“全选”就无效了)

这是因为移除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);
                }
            });
        });

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

你可能感兴趣的:(用jQuery实现复选框的全选、全不选、和反选)