js /jq 写 全选 反选 不选
HTML 结构部分
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>全/反/不选</title> </head> <body> <input type="button" value='全选'> <input type="button" value='反选'> <input type="button" value='不选'> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> </body> </html>
js写法
<script> var aInput = document.getElementsByTagName('input'); var ckb = []; for(var i=0; i<aInput.length; i++ ){ var that = aInput[i]; if(that.type == 'checkbox'){ ckb.push(that) } if(that.type == 'button' && that.value == '全选'){ that.onclick=function(){ fn(true) } } if(that.type == 'button' && that.value == '不选'){ that.onclick=function(){ fn(false) } } if(that.type == 'button' && that.value == '反选'){ that.onclick=function(){ fn(false,true) } } } function fn(t,f){ for(var j=0; j<ckb.length;j++){ var k = ckb[j]; if(f){ k.checked=!k.checked }else{ k.checked=t; } } } </script>
jQ写法
$(function(){ var btn = $('input[type=button]'); var ckb = $('input[type=checkbox]') btn.click(function(){ switch($(this).val()){ case '全选': ckb.prop('checked',true) break; case '反选': ckb.prop('checked',!ckb.prop('checked')) break; case '不选': ckb.prop('checked',false) break; } }) })