跳转至

Jquery 常用选项

1. jquery选择

    项目中需要做一个全选、全不选和反选的功能。刚接到这个需求的时候,心想很简单的一个功能,几行代码就能搞定,然而事实并非如此。下面就把我的思路说一下

  • 当点击'全选'按钮时,页面中所有的复选框都应该为选中状态,
  • 当再次点击'全选'按钮时,所有的复选框应该是非选中状态。
  • 当点击子复选框时,'全选'按钮应该是非选中状态。
  • 当选中当前页面的所有子复选框时,'全选'按钮应该是'选中'状态。
  • 点点击'全不选'按钮时,当前页面的所有复选框置为非选中状态。
  • 当点击'反选'按钮时,当前页面选中状态的复选框置为未选中状态,未选中状态的复选框置为选中状态。

2. 代码展示

代码

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>全选、全不选、反选</title>
        <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.5.0/jquery.js"></script>
        <script type="text/javascript">
            $(function () {
                //全选或全不选
                $("#all").click(function(){   
                    if(this.checked){   
                        $("#list :checkbox").prop("checked", true);  
                    }else{   
                        $("#list :checkbox").prop("checked", false);
                    }   
                }); 
                //全选  
                $("#selectAll").click(function () {
                     $("#list :checkbox,#all").prop("checked", true);  
                });  
                //全不选
                $("#unSelect").click(function () {  
                     $("#list :checkbox,#all").prop("checked", false);  
                });  
                //反选 
                $("#reverse").click(function () { 
                     $("#list :checkbox").each(function () {  
                          $(this).prop("checked", !$(this).prop("checked"));  
                     }); 
                });             
            }); 
        </script>
    </head>
    <body>
        <ul id="list">  
           <li><label><input type="checkbox" value="1"> 1.第一选择</label></li>
           <li><label><input type="checkbox" value="2"> 2.第二选择</label></li>
           <li><label><input type="checkbox" value="3"> 3.第三选择</label></li>
           <li><label><input type="checkbox" value="4"> 4.第四选择</label></li>
           <li><label><input type="checkbox" value="5"> 5.第五选择</label></li>
           <li><label><input type="checkbox" value="6"> 6.第六选择</label></li>
        </ul>
        <input type="checkbox" id="all">
        <input type="button" value="全选" class="btn" id="selectAll">  
        <input type="button" value="全不选" class="btn" id="unSelect">  
        <input type="button" value="反选" class="btn" id="reverse">  
    </body>
</html>

常规选择