实现全选,全不选,反选功能
1.JavaScript实现
2.jQuery实现
html代码
1 <div> 2 <input type="checkbox" id="selectAll">全选/全不选 3 <input type="checkbox" id="Anti-election">反选 4 </div> 5 <button type="button" id="selectAllBtn">全选/全不选</button> 6 <button type="button" id="Anti-electionBtn">反选</button> 7 <div id="shopCar"> 8 <input type="checkbox" name="checkBox">香蕉 9 <input type="checkbox" name="checkBox">苹果 10 <input type="checkbox" name="checkBox">橙子 11 <input type="checkbox" name="checkBox">葡萄 12 </div>
JavaScript代码
1 window.onload = function () { 2 var selectAll = document.getElementById("selectAll"); 3 var checkBox = document.getElementsByName("checkBox"); 4 var shopCar = document.getElementById("shopCar"); 5 var antiElection = document.getElementById("Anti-election"); 6 //反选 7 antiElection.onclick = function () { 8 for (var i = 0; i < checkBox.length; i++) { 9 checkBox[i].checked = !checkBox[i].checked; 10 } 11 }; 12 13 //全选,全不选 14 selectAll.onclick = function () { 15 if (selectAll.checked == true) { 16 for (var i = 0; i < checkBox.length; i++) { 17 checkBox[i].checked = true; 18 } 19 } 20 else { 21 for (var i = 0; i < checkBox.length; i++) { 22 checkBox[i].checked = false; 23 } 24 } 25 }; 26 //若有一个没选,则全选的checkbox为false 27 shopCar.onclick = function () { 28 for (var i = 0; i < checkBox.length; i++) { 29 var e = checkBox[i]; 30 if (e.checked) { 31 selectAll.checked = false; 32 } 33 } 34 } 35 36 }
jQuery代码
注意:$(this).attr("checked",true)的使用版本问题
1 $(document).ready(function(){ 2 var select123=true; 3 $("#selectAllBtn").click(function(){ 4 if(select123){ 5 $("input[name='checkBox']").each(function(){ 6 $(this).prop("checked",true);//在jQuery1.7版本之前可以用 $(this).attr("checked",true);之后就不行了 7 select123=false; 8 return; 9 }) 10 }else{ 11 $("input[name='checkBox']").each(function(){ 12 $(this).prop("checked",false); 13 select123=true; 14 return; 15 }) 16 } 17 18 }) 19 $("#Anti-electionBtn").click(function(){ 20 $("input[name='checkBox']").each(function(){ 21 $(this).prop("checked",!$(this).prop("checked")); 22 }) 23 }) 24 25 })