学习目标:
- JS实现一组复选框的全选,全不选,和反选
学习内容:
- 复选框的属性
- JQuery的遍历和设置属性
实现思路:
对于复选框的全选,全不选和反选的实现,首先先获得一组复选框的操作权,然后对这组复选框的checked属性进行判断。点击全选按钮时,把所有复选框的checked属性设置为true。点击全不选时,将所有的复选框的checked属性设置为false。点击反选按钮时,判断当前复选框的checked属性,true改为false,false改为true。
第一步,搭建页面元素,引入JQuery文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="checkbox" name="smoke" id="" value="" />抽烟
<input type="checkbox" name="drink" id="" value="" />喝酒
<input type="checkbox" name="hire" id="" value="" />烫头
<input type="checkbox" name="game" id="" value="" />玩游戏
<input type="checkbox" name="code" id="" value="" />敲代码
<input type="checkbox" name="fruit" id="" value="" />吃水果
<button type="button" id="all">全选</button>
<button type="button" id="disall">全不选</button>
<button type="button" id="reverse">反选</button>
</body>
<script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
</script>
</html>
第二步,实现全选的效果
$("#all").click(function(){
$("input[type=checkbox]").each(function(){
$(this).prop("checked",true);
})
})
第三步,实现全不选的效果
$("#disall").click(function(){
$("input[type=checkbox]").each(function(){
$(this).prop("checked",false);
})
})
第四步,实现反选的效果
$("#reverse").click(function(){
$("input[type=checkbox]").each(function(){
if($(this).context.checked==true){
$(this).prop("checked",false);
}else{
$(this).prop("checked",true);
}
})
})
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="checkbox" name="smoke" id="" value="" />抽烟
<input type="checkbox" name="drink" id="" value="" />喝酒
<input type="checkbox" name="hire" id="" value="" />烫头
<input type="checkbox" name="game" id="" value="" />玩游戏
<input type="checkbox" name="code" id="" value="" />敲代码
<input type="checkbox" name="fruit" id="" value="" />吃水果
<button type="button" id="all">全选</button>
<button type="button" id="disall">全不选</button>
<button type="button" id="reverse">反选</button>
</body>
<script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$("#all").click(function(){
$("input[type=checkbox]").each(function(){
$(this).prop("checked",true);
})
})
$("#disall").click(function(){
$("input[type=checkbox]").each(function(){
$(this).prop("checked",false);
})
})
$("#reverse").click(function(){
$("input[type=checkbox]").each(function(){
if($(this).context.checked==true){
$(this).prop("checked",false);
}else{
$(this).prop("checked",true);
}
})
})
</script>
</html>
效果演示
BUG记录:
本来对于复选框的checked值,打算使用attr设置属性的方法给所有的复选框设置选中和非选中效果。结果,发现出现的情况是,只有第一次的全选和全不选效果。上网查了资料才发现,attr方法对于不同的浏览器,表现形式不一样。所以在JQuery1.6以后,新增了prop方法可以对元素进行赋值操作。最终实现了效果,特此记录。