Jquery之CheckBox全选与反选

来源:互联网 发布:windows10数据库 编辑:程序博客网 时间:2024/06/05 20:29
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery之CheckBox全选与反选</title>
<script type="text/javascript" src="...jquery-3.2.1.min.js"></script>
<script>
    $(document).ready(function() {
        var i=true;
        var checkbox1=$("input:button[name='quanxuan']");
        var checkbox2=$("input:button[name='fanxuan']");
        var box=$("input:checkbox");
        //全选
        checkbox1.click(function(){
                if(i){
                        box.prop('checked',true);
                        i=false;
                        //同辈元素siblings
                        $(this).parent().find(box).siblings().css('color','red');

                }else{
                        box.prop('checked',false);
                        i=true;
                        $(this).parent().find(box).siblings().css('color','black');
                }
            });
        //反选            
        checkbox2.click(function(){
            box.each(function() {
                if($(this).prop('checked')){
                    $(this).prop('checked',false);        
                    $(this).parent().find(box).siblings().css('color','black');                
                }else{
                    $(this).prop('checked',true);
                    $(this).parent().find(box).siblings().css('color','red');
                }

             });
                
        });
        //如果被选中,字体颜色变红
        $("input:checkbox").click(
            function(){
            if($(this).prop('checked')){
                $(this).parent().find(box).siblings().css('color','red');
            }else{
                $(this).parent().find(box).siblings().css('color','black');
            }
        }
        );
        
            
    });
</script>
</head>

<body>
<div>
  <!--lable标签实现点击文字也可以选中CheckBox-->
  <label><input  type="checkbox" value="Java" /><span>Java</span></label>
  <label><input  type="checkbox" value="JavaScript" /><span>JavaScript</span></label>
  <label><input  type="checkbox" value="JavaOOP" /><span>JavaOOP</span></label>
  <label><input  type="checkbox" value="JavaAOP" /><span>JavaAOP</span></label>
  <label><input  type="checkbox" value="JQuery" /><span>JQuery</span></label>
  <br />
  <input  type="button" id="but1" name="quanxuan" value="全选"/>
  <input  type="button" name="fanxuan" value="反选"/>
</div>

</body>

</html>

原创粉丝点击