第一种,是利用事件监听来完成
布局部分的代码:
<label> 全选 <input type="checkbox" id="all"> </label> </div> <div class="check"> <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> javascript部分的代码: var allcheck = document.getElementById("all") var aCheck = document.querySelectorAll(".check>input") allcheck.addEventListener("click",function(){ for(var i=0;i<aCheck.length;i++){ aCheck[i].checked=this.checked } }) for(var i=0;i<aCheck.length;i++){ aCheck[i].addEventListener("click",function(){ var bstop=true; //俗称开关门 for(var j=0;j<aCheck.length;j++){ if(!aCheck[j].checked){ bstop=false; break; } } allcheck.checked=bstop }) } 第二种,利用数组的遍历来完成 var data=[ {id:1001,icon:"img/1.png",name:"餐饮0",num:1,price:10,selected:false}, {id:1002,icon:"img/2.png",name:"餐饮1",num:1,price:20,selected:false}, {id:1003,icon:"img/3.png",name:"餐饮2",num:1,price:30,selected:false}, {id:1004,icon:"img/4.png",name:"餐饮3",num:1,price:40,selected:false}, {id:1005,icon:"img/5.png",name:"餐饮4",num:1,price:50,selected:false}, {id:1006,icon:"img/6.png",name:"餐饮5",num:1,price:60,selected:false}, {id:1007,icon:"img/7.png",name:"餐饮6",num:1,price:70,selected:false}, {id:1008,icon:"img/8.png",name:"餐饮7",num:1,price:80,selected:false}, {id:1009,icon:"img/9.png",name:"餐饮8",num:1,price:90,selected:false}, {id:1010,icon:"img/10.png",name:"餐饮9",num:1,price:100,selected:false} ]; //在页面上生成选框 var str="<ul>"; str+="<li><input type='checkbox' class='allCheck'></li>"; data.forEach(function (t) { str+="<li><input type='checkbox' class='checkbox'></li>"; }); str+="</ul>"; document.body.innerHTML+=str;// 获取所有的input元素 var inputs=document.getElementsByTagName("input"); var checks=Array.from(inputs); checks.forEach(function (t) { // t就是每个input t.addEventListener("click",clickHandler); });
function clickHandler(e) { // console.log(this);//this就是被点击的input var index=checks.indexOf(this); // arr这个数组就是除了全选以外其他input的数组 var arr=checks.slice(1); if(index===0){ // 如果点击是第0个,也就是全选 var bool=this.checked; arr.forEach(function (t) { // 让每个不是全选input的元素都和全选这个input的checked相同 t.checked=bool; }) }else{ var bool1=arr.every(function (t) { return t.checked; }); checks[0].checked=bool1; } }