jQuery选择器实现复选框的全选、全不选和反选功能

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
  
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //用id选择器获取button组件,这里可以用其他选择器,如class为. id为# 等。详情看jQuery官网
            $("#selectAll").click(function () {
                //设置选择框选中为true
                $("input[type='checkbox']").prop("checked", true);
            });
 
            $("#selectNone").click(function () {
                //设置选择框选中为false
                $("input[type='checkbox']").prop("checked", false);
            });
            
            $("#inverseSelect").click(function () {
                $("input[type='checkbox']").each(function () {
                    //设置选择框选中的取反
                    this.checked = !this.checked;
                })
            });
        });
    </script>
</head>

<body>

    <h3>你爱好的运动是?:</h3>

    <input type="checkbox"/>足球
    <input type="checkbox"/>篮球
    <input type="checkbox"/>羽毛球
    <input type="checkbox"/>乒乓球

    <br>
    <input type="button" id="selectAll" value="全选">
    <input type="button" id="selectNone" value="全不选">
    <input type="button" id="inverseSelect" value="反选">

</body>

</html>

 

posted @ 2021-03-18 11:27  MyNorth  阅读(200)  评论(0)    收藏  举报