第一次可以,怎么第二次,下面的不全选了,但是实际是选中的,只是没有(√)钩上
html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script src="jquery-1.11.2.min.js"></script> </head> <body> <table width="200" border="1" style=" text-align: center;"> <tbody> <tr> <th><input type="checkbox" class="check-all" /> 全选</th> <th>序号</td> </tr> <tr> <td><input type="checkbox" /></td> <td>1</td> </tr> <tr> <td><input type="checkbox" /></td> <td>2</td> </tr> <tr> <td><input type="checkbox" /></td> <td>3</td> </tr> <tr> <td><input type="checkbox" /></td> <td>4</td> </tr> <tr> <td><input type="checkbox" /></td> <td>5</td> </tr> <tr> <th><input type="checkbox" class="check-all" /> 全选</th> <th>序号</td> </tr> </tbody> </table> <br><br> <button id="btn5">选中个数</button> <script type="text/javascript"> $(function(){ $(".check-all").on("click", function(){ console.log($(this).attr("checked")) console.log($(this).attr("checked") == 'checked') if($(this).attr("checked")) { $('input[type="checkbox"]').removeAttr("checked");//取消全选 } else { $('input[type="checkbox"]').attr("checked", true);//全选 } }); $("#btn5").click(function(){ var length = $('input[type="checkbox"][checked]').length; alert(length); }) }); </script> </body> </html>
使用prop('checked', true),attr方法
有兼容问题