js實現全選和全不選功能
阿新 • • 發佈:2020-07-29
本文例項為大家分享了js實現全選和全不選的具體程式碼,供大家參考,具體內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>操作複選框</title> </head> <body> <input type="checkbox" id="quan"> 全選<br> <input type="checkbox" name="aihao">遊戲<br> <input type="checkbox" name="aihao">睡覺<br> </body> </html> <script type="text/javascript"> window.onload=function () { var firstChecbox = document.getElementById("quan"); var aihao=document.getElementsByName("aihao"); //完成全選和全不選 //當單擊全選時使下方的checkbox中的checked屬性為true firstChecbox.onclick=function () { //遍歷下方的checkbox //使每一個複選框的屬性中的checked和全選的屬性保持一致即可實現(不完善) for (let i = 0; i <aihao.length ; i++) { aihao[i].checked=firstChecbox.checked; } } //如果選中的數量和愛好的總數量一致的就把全選給選中,否則不全選 //為每一個aihao繫結單擊事件 var all=aihao.length; for (let i = 0; i < aihao.length; i++) { //繫結單擊事件 aihao[i].onclick=function () { //定義選中的數量 var checkedCount=0; for (let i = 0; i < aihao.length; i++) { //如果愛好選中就把選中的數量+1; if (aihao[i].checked){ checkedCount++; } //如果選中的數量和總數相當就把全選給勾選 if (checkedCount==all){ firstChecbox.checked=true } else{ firstChecbox.checked=false; } } } } } </script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。