jQuery实现按钮的全选

 jquery相对js实现就比较简单

<input type="checkbox" id="all"><br>
<input type="checkbox" name="sub"/>1<br>
<input type="checkbox" name="sub"/>2<br>
<input type="checkbox" name="sub"/>3<br>
<input type="checkbox" name="sub"/>4
<script src="js/jquery-1.12.4.js"></script>
<script>
    $("#all").on("click",function () {
        if(this.checked){
            $("input[name='sub']").attr("checked",true);
        }else {
            $("input[name='sub']").attr("checked",false);
        }
    })
</script>

但是这样实现全选和取消全选,有点问题,第一次全选和取消全选后,第二次再点击全选,就会失效。这个时候用prop()方法可以解决这个问题。将js代码替换成下列代码即可以实现按钮的全选和取消全选。

$("#all").on("click",function () {
    $("input[name='sub']").prop('checked',this.checked);
});
$("input[name='sub']").on("click",function () {
    var $sub=$("input[name='sub']");
    $("#all").prop("checked" , $sub.length == $sub.filter(":checked").length ? true :false);
})

猜你喜欢

转载自blog.csdn.net/m0_60237095/article/details/129832286