复选框的全选反选实现(即购物车的复选框实现)

    xiaoxiao2021-03-25  43

    这周工作时在做全选时遇到卡壳,趁着闲暇时间整理一下全选的的几种实现方式。 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(){ 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; });

    转载请注明原文地址: https://ju.6miu.com/read-37041.html

    最新回复(0)