利用jQuery实现CheckBox全选/全不选/反选

jQuery有些版本中实现CheckBox全选/全不选/反选会有bug,经测试jquery-1.3.1.js–>测试通过,jquery-1.5.1.js–>测试不通过。

实现CheckBox全选/全不选/反选代码如下:

<%@ page language="java" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>复选框全选/全不选/反选</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">
  <script type="text/javascript"
   src="<%=request.getContextPath()%>/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>
 </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="反 选"/> 
 </body>
</html>

原文地址:https://www.cnblogs.com/linjiqin/p/3148259.html