<script> //點擊全選,子復選框被選中 function demo(){ var allcheck=document.getElementById("allcheck"); var choice=document.getElementsByName("choice"); for(var i=0;i<choice.length;i++){ choice[i].checked=allcheck.checked; } } //點擊子復選框,全選框 選中、取消 function setAll(){ if(!$(".checknum").checked){ $("#allcheck").prop("checked",false); // 子復選框某個不選擇,全選也被取消 } var choicelength=$("input[type='checkbox'][class='checknum']").length; var choiceselect=$("input[type='checkbox'][class='checknum']:checked").length; if(choicelength==choiceselect){ $("#allcheck").prop("checked",true); // 子復選框全部部被選擇,全選也被選擇;1.對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法;2.對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。 } } </script> <body> <input type="checkbox" id="allcheck" onclick="demo()" />全選 <input type="checkbox" name="choice" class="checknum" onclick="setAll()" />1 <input type="checkbox" name="choice" class="checknum" onclick="setAll()" />2 <input type="checkbox" name="choice" class="checknum" onclick="setAll()" />3 <input type="checkbox" name="choice" class="checknum" onclick="setAll()" />4 </body>