我的代码,不知道为什么全选和全不选在第一次打开时点击有效,再点击就没勾上了,但是审查元素是看到其checked改变了的。
<!DOCTYPE html>
<html lang="zh-hans">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form action="" method="" enctype="">
<p class="text-center"><input type="checkbox" name="items" value="football"/>足球</p>
<p class="text-center"><input type="checkbox" name="items" value="basketball"/>篮球</p>
<p class="text-center"><input type="checkbox" name="items" value="badminton"/>羽毛球</p>
<p class="text-center"><input type="checkbox" name="items" value="tennis"/>乒乓球</p>
</form>
<p class="text-center">
<button class="btn btn-default" id="checkall">全选</button>
</p>
<p class="text-center">
<button class="btn btn-default" id="nocheck">全不选</button>
</p>
<p class="text-center">
<button class="btn btn-default" id="check1">反选</button>
</p>
</div>
<script>
$(document).ready(function(){
$('#checkall').click(function(){
$('[name=items]:checkbox').attr('checked',true);
});
$('#nocheck').click(function(){
$('[name=items]:checkbox').attr('checked',false);
});
$('#check1').click(function(){
//alert(123);
$('[name=items]:checkbox').each(function(){
this.checked=!this.checked;
});
});
});
</script>
</body>
</html>
将attr
改成prop
,http://api.jquery.com/prop/#prop-propertyName 有详细的介绍
楼上正解,jquery1.6以后用prop
php
$(document).ready(function(){ $('#checkall').click(function(){ $('[name=items]:checkbox').prop('checked',true); }); $('#nocheck').click(function(){ $('[name=items]:checkbox').prop('checked',false); }); $('#check1').click(function(){ $('[name=items]:checkbox').each(function(){ this.checked=!this.checked; }); }); });