jquery -全选/反选

来源:互联网 发布:mvc索引超出数组界限 编辑:程序博客网 时间:2024/05/11 20:46
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>jquery基础-3全选、反选</title>
<script type="text/javascript" src="../js/jquery.min.js"></script>
</head>

<body>
    <table width="50%" border="1" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="14%"><input type="checkbox" name="first" /></td>
    <td width="45%">1</td>
    <td width="41%">&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="nine" /></td>
    <td>2</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="second" /></td>
    <td>3</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="third" /></td>
    <td>4</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="four" /></td>
    <td>5</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="five" /></td>
    <td>6</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="six" /></td>
    <td>7</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="seven" /></td>
    <td>8</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="eight" /></td>
    <td>9</td>
    <td>&nbsp;</td>
  </tr>
</table>
    <div align="center">
      <input type="checkbox" id="all" />
      全选
      <input type="checkbox" id="invert" />
      反选
    </div>
</body>
</html>
<script>
    $(function(){
        //全选
        $("#all").on("click",function(){
            if(this.checked){
                $("table tr td input[type=checkbox]").attr("checked",true);
                $("#invert").attr('checked',false);
            }else{
                $("table tr td input[type=checkbox]").attr("checked",false);
            }
        });
        
        // 反选
        $("#invert").on("click",function() {
            if($("#all").attr('checked')=="checked"){
                $("#all").attr('checked',false);
            }   
            $('table tr td input[type=checkbox]').each( function() {     
                $(this).attr("checked", !$(this).attr("checked"));     
        });     
    });
        
    });
</script>

原创粉丝点击