jQuery 全选,反选的初级实现

一、如图所示

这里写图片描述

二、代码实现及说明

html代码主要部分

内容列表的表头
<table>
    <tr><input type="checkbox" id="all"><input type="checkbox" id="reverse">
<tr/>
    <tr><input type="checkbox" class="child"><tr/>
    <tr><input type="checkbox" class="child"><tr/>
    <tr><input type="checkbox" class="child"><tr/>
</table>

jQuery代码部分

$(function(){
    $("#all").click(function(){
        var flag = $(this).is(":checked");   -->下面有解释
        if(flag) $(".child").attr("checked", true);
        else $(".child").attr("checked", false);
    });

    $("#reverse").click(function(){
        $(".child").each(function(){
          $(this).attr("checked", !$(this).is(":checked"));
        });
    });
});

1、 为什么使用$(this).is(“:checked”); ?
此代码是获取当前的复选框是否选中的,选中返回true 。

有的小伙伴可能想到了$(this).attr(“checked),可以尝试

下alert(typeof $(this).attr(“checked)) 返回的是undefined

最后:安利下我用的制作本文开头gif图片的工具Licecap,很好用
https://www.cockos.com/licecap/

猜你喜欢

转载自blog.csdn.net/gao_zhennan/article/details/81089181