jQuery复选框-全选、全不选

    xiaoxiao2025-05-18  8

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>练习-复选框</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!-- 记得引入jquery-1.11.3.js文件到js目录下 --> <script type="text/javascript" src="js/jquery-1.11.3.js"></script> <style type="text/css"> body{ font-family: "Microsoft YaHei"; text-align: center; } #mainDiv { width: 100%; text-align: center; margin-top:10px; } </style> <script type="text/javascript"> /* To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method. 根据官方的建议:具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(), 其他的使用 attr() */ $(document).ready(function(){ //1. 全选/全不选 $("#all").click(function(){ //分析: 子复选框状态,与父复选框状态一致 // 1.1 获取当前复选框状态 var flag = this.checked; // this 是dom元素 // 1.2 选取子复选框,设置状态(父复选框状态) //$(":checkbox[name='course']").attr("checked",flag); $(":checkbox[name='course']").prop("checked",flag); }); //2. 反选 $("#btn1").click(function(){ $(":checkbox[name='course']").each(function(){ //2.1 获取当前选中状态 var flag = $(this).prop("checked"); //2.2 反选 $(this).prop("checked", !flag); }); clickCourse(); }); //3.将选中的设置为没有选中 $("#btn2").click(function(){ $(":checkbox[name='course']:checked").each(function(){ //this.checked = false; $(this).prop("checked", false); }); clickCourse(); }); //4. 将没有选中的设置为选中 $("#btn3").click(function(){ $(":checkbox[name='course']:not(:checked)").each(function(){ //this.checked = true; $(this).prop("checked", true); }); clickCourse(); }); //5. 给子复选框添加事件 // 当选中的子复选框长度 == 子复选框总长度, 父复选框选中; // 否则,父复选框取消选中 $(":checkbox[name='course']").click(clickCourse); // 点击每一个自复选框,判断是否选择父复选框 function clickCourse(){ if ($(":checkbox[name='course']:checked").length == $(":checkbox[name='course']").length) { $("#all").prop("checked",true); }else{ $("#all").prop("checked",false); } } }); </script> </head> <body> <div id="mainDiv"> <p>itcast学科选择:<input type="checkbox" name="courseAll" id="all"><label for="all">全选/全不选</label></p> <input type="checkbox" name="course" value="Java" id="java" > <label for="java">Java</label> <input type="checkbox" name="course" value="IOS" id="ios" > <label for="ios">IOS</label> <input type="checkbox" name="course" value="Android" id="android" > <label for="android">Android</label> <input type="checkbox" name="course" value=".Net" id="net" > <label for="net">.Net</label> <input type="checkbox" name="course" value="PHP" id="php" > <label for="php">PHP</label> <input type="checkbox" name="course" value="网页平面" id="ui" > <label for="ui">网页平面</label> </div> <br><br> <hr> <input type="button" id="btn1" value="反选"> <input type="button" id="btn2" value="将选中的设置为没有选中"> <input type="button" id="btn3" value="将没有选中的设置为选中"> </body> </html>
    转载请注明原文地址: https://ju.6miu.com/read-1299008.html
    最新回复(0)