导航首页 » 技术教程 » jQuery对checkbox 复选框的全选全不选反选的操作
jQuery对checkbox 复选框的全选全不选反选的操作 87 2024-02-22   

先给大家展示下效果图,如果大家感觉还不错,请继续参考实现代码。

查看图片

HTML代码:

<body>
<ul id="list"> 
<li><label><input type="checkbox" name="items" value="1"> 1.时间都去哪儿了</label></li> 
<li><label><input type="checkbox" name="items" value="2"> 2.海阔天空</label></li> 
<li><label><input type="checkbox" name="items" value="3"> 3.真的爱你</label></li> 
<li><label><input type="checkbox" name="items" value="4"> 4.不再犹豫</label></li> 
<li><label><input type="checkbox" name="items" value="5"> 5.光辉岁月</label></li> 
<li><label><input type="checkbox" name="items" value="6"> 6.喜欢??</label></li> 
</ul> 
<input type="checkbox" id="all"> 全选/全不选</br>
<input type="button" value="全选" class="btn" id="selectAll"> 
<input type="button" value="全不选" class="btn" id="unSelect"> 
<input type="button" value="反选" class="btn" id="reverse"> 
<input type="button" value="获得选中的所有值" id="btn" id="getValue">
</body>

jquery代码:

<script type="text/javascript">
$(function(){
//全选/全不选
$("#all").click(function(){
$("[name=items]:checkbox").attr("checked",this.checked);
});
$("[name=items]:checkbox").click(function(){
var flag=true;
$("[name=items]:checkbox").each(function(){
if(!this.checked){
flag=false;
}
});
$("#all").attr("checked",flag);
})
//全选
$("#selectAll").click(function(){
$("[name=items]:checkbox").each(function(){
$(this).attr("checked",true);
});
});
//全不选
$("#unSelect").click(function(){
$("[name=items]:checkbox").each(function(){
$(this).attr("checked",false);
});
});
//反选
$("#reverse").click(function(){
$("[name=items]:checkbox").each(function(){ //遍历每一个复选框
//$(this).attr("checked",!$(this).attr("checked")); //jQuery方法取复选框的反向值
this.checked=!this.checked; //js方法
});
});
//输出选中的值
$("#btn").click(function(){
var str="你选中的是:rn";
$("[name=items]:checkbox:checked").each(function(){
str+=$(this).val()+"rn";
});
alert(str);
});
})
</script>

注:由于jquery版本的变更,新版本出现只能点击一次,老一点的版本是可以的,新的版本不可以使用attr来设置选中状态了,第一种解决方法是可以使用js原生的方法this.checked=true/false;

第二种解决方法是把attr换成prop。

以上所述是小编给大家介绍的jQuery对checkbox 复选框的全选全不选反选的操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对绿夏网网站的支持!



!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103