温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用原生JS实现简单的多选框功能

发布时间:2020-10-15 03:13:43 来源:脚本之家 阅读:133 作者:码农的N次方 栏目:web开发

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<input id="cheakAll" type="checkbox">全选
<div>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
</body>
</html>
<script>
//找到全选按钮
var oChkAllBtn=document.getElementById('cheakAll');
var oDiv=document.getElementsByTagName('div')[0];
var aInput=oDiv.getElementsByTagName('input');
var n=0; //计数器
//alert(aInput.length);
//点击全选按钮,让其他的全部选中
oChkAllBtn.onclick=function(){
//判断我是什么状态
/*if(this.checked==true){
for(var i=0; i<aInput.length; i++){
aInput[i].checked=true;
}
}else{
for(var i=0; i<aInput.length; i++){
aInput[i].checked=false;
}
}*/
for(var i=0; i<aInput.length; i++){
if(this.checked==true){//判断全选按钮自己的状态
aInput[i].checked=true;
n=aInput.length; //控制计数器
}else{
aInput[i].checked=false;
n=0; //控制计数器
}
};
};
//--------------------------------------------
//每一个按钮绑定事件
for(var j=0; j<aInput.length; j++){
aInput[j].onclick=function(){
//如果我自己是cheaked状态 n++ 否则 n--
if(this.checked==true){
n++;
}else{
n--;
};
//console.log(n);
//如果n==aInput.length
if(n==aInput.length){
oChkAllBtn.checked=true;
}else{
oChkAllBtn.checked=false;
}
};
};
</script>

以上所述是小编给大家介绍的用原生JS实现简单的多选框功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI