html页面
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>测试页面</title>
- <script src = "jquery.js"></script>
- <script src = "test.js"></script>
- </head>
- <body>
- <input type = "checkbox" id = "allCheck"/>全选</th><br/>
- <input type = "checkbox" name = "check"/></th>
- <input type = "checkbox" name = "check"/></th>
- <input type = "checkbox" name = "check"/></th>
- <input type = "checkbox" name = "check"/></th>
- </body>
- </html>
js代码
第一种方式 (有点不靠谱)
- //全选框
- $("#allCheck").click(function(){
-
//console.log($(this).get(0).checked);
console.log($(this).is(":checked"));
//看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
//console.log($(this).attr('checked'));
if($(this).is(":checked")){ if($(this).attr("checked")){ - $("input[name='check']").attr("checked",true);
- }else{
- $("input[name='check']").attr("checked",false);
- }
- })
- //单选框
- $("input[name='check']").change(function(){
- if($("input[name='check']").not("input:checked").size() <= 0){
- $("#allCheck").attr("checked",true);
- }else{
- $("#allCheck").attr("checked",false);
- }
- })
第二种方式
- 全选框
- $("#allCheck").click(function(){
- $("input[name='check']").prop("checked",this.checked);
- })
- //单选框
- $("input[name='check']").change(function(){
- if($("input[name='check']").not("input:checked").size() <= 0){
- $("#allCheck").prop("checked",true);
- }else{
- $("#allCheck").prop("checked",false);
- }
- })
第三种方式(原生js)
- //全选框
- $("#allCheck").click(function(){
- var a = document.getElementById("allCheck");
- var b = document.getElementsByName("check");
- if(a.checked){
- for(var i = 0; i < b.length; i++){
- b[i].checked = true;
- }
- }else{
- for(var i = 0; i < b.length; i++){
- b[i].checked = false;
- }
- }
- })
- //单选框
- $("input[name='check']").click(function(){
- var flag = true;
- var a = document.getElementById("allCheck");
- var b = document.getElementsByName("check");
- for(var i = 0; i < b.length; i++){
- if(!b[i].checked){
- flag = false;
- break;
- }
- }
- a.checked = flag;
- });