<html><head> <script src="jquery-1.11.1.min.js" type="text/javascript"></script></head><body> <input type="checkbox" name="chk_list[]" value="1" />1 <input type="checkbox" name="chk_list[]" value="2" />2 <input type="checkbox" name="chk_list[]" value="3" />3 <input type="checkbox" name="chk_list[]" value="4" />4 <input type="checkbox" name="chk_all" id="chk_all" />全选/取消全选<script type="text/javascript"> $("#chk_all").click(function(){ // 使用attr只能执行一次 $("input[name="chk_list[]"]").attr("checked", $(this).attr("checked")); // 使用prop则完美实现全选和反选 $("input[name="chk_list[]"]").prop("checked", $(this).prop("checked")); // 获取所有选中的项并把选中项的文本组成一个字符串 var str = ""; $($("input[name="chk_list[]"]:checked")).each(function(){ str += $(this).next().text() + ","; }); alert(str); });</script></body></html>总结:$(".chooseall").click(function(){ if($(".chooseall").attr("checked") == "checked"){$("input[name="checkbox1"]").removeAttr("checked","checked"); console.log(1); }else{ $("input[name="checkbox1"]").attr("checked","checked"); console.log(2); }});
除了第一个checkbox之外,其余的都是ajax动态生成的,跟这个有关系么?console.log每次点击的都能交替输出1和2,但就是中间的代码不能执行。
解决方案:
removeAttr参数只需要一个,removeAttr("checked")
不过建议替换成
$(".chooseall").click(function(){ if($(".chooseall").prop("checked") == true){ $("input[name="checkbox1"]").prop("checked", false); console.log(1); }else{ $("input[name="checkbox1"]").prop("checked", false); console.log(2); }});或者更简洁的,$(".chooseall").click(function(){ var isChecked = $(this).prop("checked"); $("input[name="checkbox1"]").prop("checked", isChecked);});