jQuery实现CheckBox全选、全不选

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery实现CheckBox全选、全不选</title>
<script src="http://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>    
<script type="text/javascript">
        $(function() {
		$(':checkbox').click(function(evt){
            // 阻止冒泡
            evt.stopPropagation();
        });
        	//判断是否全选
           $("#checkAll").click(function() {
                $('input[name="subBox"]').prop("checked",this.checked);  
            });
            
            var $subBox = $("input[name='subBox']");
            $subBox.click(function(){
            	//alert($subBox.length);
            	//alert($("input['subBox']:checked").length);
                $("#checkAll").prop("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false);
            });
            
            //用于检查是否选中,选中的话提示值
            $("#butt").click(function (){
            	//$('input[name="subBox"]').prop("checked",this.checked); 
		    	var arrChk=$("input[name='subBox']:checked");
			    $(arrChk).each(function(){   //each()  遍历函数
			       alert(this.value);                        
			    }); 
			    if(arrChk.length==0){
			    	alert("没有选中")
			    }
            });

        });
        
    </script>
 
</head>
<body>
    <div>
        <input id="checkAll" type="checkbox" />全选
        <input name="subBox" type="checkbox" value="1" />选项1
        <input name="subBox" type="checkbox" value="2"/>选项2
        <input name="subBox" type="checkbox" value="3"/>选项3
        <input name="subBox" type="checkbox" value="4"/>选项4
        <input type="button" id="butt"  value="检查是否选中"/>
    </div>
</body>
</html>


jQuery版本问题

原本操作属性用的是 $("XXX").attr("attrName");
而jQuery的版本用的是2.1.1,这就是存在一个兼容性和稳定性问题。 
jQuery API明确说明,1.6+的jQuery要用prop,尤其是checkBox的checked的属性的判断,
即 使用代码如下: 
$("input[name='checkbox']").prop("checked"); 
$("input[name='checkbox']").prop("disabled", false); 
$("input[name='checkbox']").prop("checked", true); 
于是乎将attr改为prop,问题得解。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值