jquery 全选 取消全选 反选

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src='./jquery.min.js'></script>
</head>
<body>
	<a href="javascript:void(0)">全选</a>
	<a href="javascript:void(0)">反选</a>
	<hr>
	<input type="checkbox"><br>
	<input type="checkbox"><br>
	<input type="checkbox"><br>
	<input type="checkbox"><br>
	<input type="checkbox"><br>
	<input type="checkbox"><br>
	<script>
		$(document).ready(function(){
			//全选 取消全选
			var flag=false;
			$('a:first').click(function(){
				//方法一
				if(flag){
					$(':checkbox').removeAttr('checked');
					$('a:first').html('全选');
					flag=false;
				}else{
					$(':checkbox').attr('checked','checked');
					
					$('a:first').html('取消全选');
					flag=true;
				}
				//方法二
				/*if(flag){
					$(':checkbox').prop('checked',false);
					$('a:first').text('全选');
				}else{
					$(':checkbox').prop('checked',true);
					$('a:first').text('取消全选');
				}
				flag=!flag;
				*/
			});

			//反选
			$('a:last').click(function(){
				$(':checkbox').each(function(index, element){
					//$(this).prop('checked',!$(this).prop('checked')); //方法一
					$(element).prop('checked',!$(this).prop('checked')); //方法二
				});
			});	
		});
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zht_123/article/details/90143461