首页 新闻 会员 周边

checkbox的状态切换只在第一次选中和非选中执行时有效

0
[已解决问题] 解决于 2017-05-22 16:25
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
function clc(){
        //alert验证代码块是否执行
         alert($("#all").is(':checked'))
        //根据all的选中状态切换全体状态
     if($("#all").is(":checked")){
         $("input[type = 'checkbox']").attr("checked",true)
     }else{
         $("input[type = 'checkbox']").attr("checked",false)
       }
}
</script>
</head>

<body>
<input type="checkbox" id="all" onclick="clc()"/><br/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
</body>

</html>
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
function clc(){
        //alert验证代码块是否执行
         alert($("#all").is(':checked'))
        //根据all的选中状态切换全体状态
     if($("#all").is(":checked")){
         $("input[type = 'checkbox']").attr("checked",true)
     }else{
         $("input[type = 'checkbox']").attr("checked",false)
       }
}
</script>
</head>

<body>
<input type="checkbox" id="all" onclick="clc()"/><br/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
</body>

</html>

通过ID为all的选中状态,控制所有的checkbox选中。

在初次切换时,全选和全消有效。

但是第二次点击选中和取消就不会有选中状态的切换了,只有alert能表明确实进入代码块执行了。

charles999的主页 charles999 | 菜鸟二级 | 园豆:204
提问于:2017-05-22 10:42
< >
分享
最佳答案
1
function clc(){
        //alert验证代码块是否执行
         alert($("#all").is(':checked'))
        //根据all的选中状态切换全体状态
     if($("#all").is(":checked")){
         $("input[type = 'checkbox']").prop("checked",true)
     }else{
         $("input[type = 'checkbox']").prop("checked",false)
}}

js方法中attr方法更换为prop就可以了

奖励园豆:5
| 菜鸟二级 |园豆:332 | 2017-05-22 15:15
| 园豆:332 (菜鸟二级) | 2017-05-22 15:21

非常谢谢,问题解决了。

charles999 | 园豆:204 (菜鸟二级) | 2017-05-22 16:19
其他回答(1)
1

用 .prop() 方法来代替:

$("input[type = 'checkbox']").prop("checked", true)

by.Genesis | 园豆:2719 (老鸟四级) | 2017-05-22 10:58

 

谢谢,问题解决了

支持(0) 反对(0) charles999 | 园豆:204 (菜鸟二级) | 2017-05-22 16:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册