全选,全不选,反选

先写一个简单的结构如下,主要看方法

                <input type="checkbox" name="" id="checkboxAll" value="" />全选/全不选<br />
		<input type="checkbox" name="items" id="" value="" />足球
		<input type="checkbox" name="itmes" id="" value="" />篮球
		<input type="checkbox" name="itmes" id="" value="" />排球
		<input type="checkbox" name="itmes" id="" value="" />橄榄球<br />
		<input type="button" name="" id="btn1" value="全选" />
		<input type="button" name="" id="btn2" value="全不选" />
		<input type="button" name="" id="btn3" value="反选" />
		<input type="button" name="" id="btn4" value="提交" />
 下面是用JQ写的方法
               <script type="text/javascript">
			var $items=$(':checkbox').not('#checkboxAll');
			//全选/全不选
			$('#checkboxAll').click(function(){
				//console.log($items.prop('checked'))
				$items.prop('checked',!$(this.prop('checked'))
			});
			//反选
			$('#btn3').click(function(){
				$items.each(function(index,val){
					console.log(this.checked)//打印的是布尔值false就是没有选中 true选中
					
					this.checked=!this.checked; 
				})
				//当点击反选的时候,全选选框实时更新。
				$('#checkboxAll').prop('checked',$items.filter(':checked').length==4)
				//下面结果跟上面一样
				//$('#checkboxAll').prop('checked',$items.filter(':not(:checked)').length==0)
				
			})
			//全选、全不选自动更新
			
			$items.click(function(){
				$('#checkboxAll').prop('checked',$items.filter(':checked').length==4)
			})
			
		</script>


猜你喜欢

转载自blog.csdn.net/qq_41831345/article/details/79774052