今天打算用jQuery實現一下復選框的全選、全不選和反選問題,剛開始用的是attr("checked",true/false)方法,發現只能在最開始實現一次全選,可以實現全不選,無法實現反選,總之調試了好久死活得不到想要的效果。最後發現,jquery 1.7.2之前支持attr對固有屬性的操作,後面的版本只能用prop了。詳細了解jQuery中attr()和prop()的區別,請點擊參考。
下面貼上我的代碼以供參考:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全選、全不選、反選</title>
<style type="text/css">
#choose input {
display: block;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var $choose = $("#choose input");
//全選
$("#all").click(function(){
$choose.each(function(){
$(this).prop("checked",true);
});
});
//全不選
$("#not").click(function(){
$choose.prop("checked",false);
});
//反選
$("#reverse").click(function(){
$choose.each(function(){
$(this).prop("checked",!$(this).prop("checked"));
});
});
});
</script>
</head>
<body>
<div id="box-function">
<input id="all" type="button" value="全選" />
<input id="not" type="button" value="全不選" />
<input id="reverse" type="button" value="反選" />
</div>
<div id="choose">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
</body>
</html>
全文完,歡迎各位前輩批評指正!