jquery1.11.1版本完成对checkbox的操作
1. 使用属性prop设置选中状态
2.使用:checked和:not(:checked)获取选中的元素
源码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>测试CheckBox</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> <style> div.content{ width:30%; margin:auto; border:1px dotted #0000ff; background-color: #ffa0a0; padding:10px; } div.sel span{ display: block; } .mt_s{ margin-top:5px; } </style> </head> <body> <div class="content"> <h1>测试CheckBox</h1> <div class="sel mt_s"> <span >按钮1<input type="checkbox" class="c1"></span> <span>按钮2<input type="checkbox" class="c2"></span> <span>按钮3<input type="checkbox" class="c3"></span> <span>按钮4<input type="checkbox" class="c4"></span> <span>按钮5<input type="checkbox" class="c5"></span> </div> <div class="op mt_s"> <button onclick="selectAll(true)">全选</button> <button onclick="selectAll(false)">全消</button> <button onclick="getCheck(true)">获取选择数据</button> <button onclick="getCheck(false)">获取未选择数据</button> </div> <div class="sta mt_s"> <span class="blue"><strong>结果:</strong></span><span class="status"></span> </div> </div> <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script> "use strict"; //全选/取消全选 function selectAll(bcheck){ var sel = getsel(); log(sel); sel.prop("checked",bcheck); } //获取选中/未选中的记录 function getCheck(bcheck){ var sel = getsel(); var c; if(bcheck){ c = sel.filter(":checked"); } else{ c = sel.filter(":not(:checked)"); } setStatus(c); } //获取全部checkbox function getsel(){ return $(".sel input:checkbox"); } //更新查询结果 function setStatus(s){ var cName=""; log(s); for(var i=0;i<s.length;i++){ cName +=$(s[i]).attr("class"); if(i<s.length-1){ cName +="," } } cName = cName==""?"没有数据":cName; $(".status").text(cName); } //记录控制台信息 function log(s){ console.log(s); } </script> </body> </html>
效果图: