×

用JS实现CheckBox全选/全不选/反选

作者:Terry2017.02.22来源:Web前端之家浏览:9540评论:0
关键词:checkbox

用JS实现CheckBox全选/全不选/反选,分享出来玩玩。

<!DOCTYPE html>
<html>
<head>  
 <title>复选框全选/全不选/反选 -Web前端之家</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
</head>
<body>
  <input type='checkbox' name='ckb' value="0"/>白羊座
  <input type='checkbox' name='ckb' value="1"/>狮子座
  <input type='checkbox' name='ckb' value="2"/>水瓶座
  <input type='checkbox' name='ckb' value="3"/>射手座<br/>
  <input type="button" onclick="allCkb('ckb')" value="全 选"/>
  <input type="button" onclick="unAllCkb()" value="全不选"/>
  <input type="button" onclick="inverseCkb('ckb')" value="反 选"/> 
   <script type="text/javascript" src="/js/jquery-1.3.1.js"></script>
   <script type="text/javascript"> 
   /**
    * 全选
    * 
    * items 复选框的name
    */
   function allCkb(items){
     $('[name='+items+']:checkbox').attr("checked", true);
   }
     
   /**
    * 全不选
    * 
    */
   function unAllCkb(){
     $('[type=checkbox]:checkbox').attr('checked', false);
   }
     
   /**
    * 反选
    * 
    * items 复选框的name
    */
   function inverseCkb(items){
     $('[name='+items+']:checkbox').each(function(){
      //此处用jq写法颇显啰嗦。体现不出JQ飘逸的感觉。
     //$(this).attr("checked", !$(this).attr("checked"));
    
     //直接使用js原生代码,简单实用
     this.checked=!this.checked;
     });
   }
   
   </script>
</body>
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/biji28.html

网友评论文明上网理性发言 已有0人参与

发表评论: