时间:2021-07-01 10:21:17 帮助过:5人阅读
代码需求, 使用attr只能执行一次,使用prop则完美实现全选和反选,获取所有选中的项并把选中项的文本组成一个字符串。
解决方案一:
代码如下:
<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>
总结:
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
参考 //www.gxlcms.com/article/62308.htm
解决方案二:
问题描述:
$(".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);
});
以上是Jquery全选与反选点击执行一次的解决方案,希望对大家有所帮助。