checkbox全选

遇到要写checkbox全选的时候,每次都要到网上搜一遍,这次记录下来,一劳永逸,省得以后老是忘记!

代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<style>
    * {
        margin: 0px;
        padding: 0px;
    }

    body {
        padding-left: 10px;
    }
</style>
<body>
<input type="checkbox" onclick="checkAll(this);" id="check_all"/> 全选/全不选
<button onclick="add();">添加</button>
<button onclick="remove();">删除</button>
<ul>
</ul>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
    function checkAll(source) {
        var checked = $(source).is(":checked");
        if (checked) {
            $("ul").find("input[type=checkbox]").not(":checked").prop("checked", checked);
        } else {
            $("ul").find("input[type=checkbox]:checked").prop("checked", checked);
        }
    }
    function check(source) {
        if ($("#check_all").is(":checked") && !$(source).is(":checked")) {
            $("#check_all").prop("checked", false);
        }
    }
    function add() {
        $("ul").append("<ol><input type='checkbox' onclick='check(this);'/> 选项--" + ($("ul").find("ol").length + 1) + "</ol>");
    }
    function remove() {
        if (!$("ul").find("input[type=checkbox]:checked").length) {
            alert("请选择要操作的选项");
            return;
        }
        $("ul").find("input[type=checkbox]:checked").parent().remove();
        $("#check_all").prop("checked", false);
    }
</script>
</html>

  在设置checkbox的选中/未选中有一个需要注意的问题就是要使用prop方法来实现,而不要使用attr,会有bug。
  这样做的主要原因是对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
  checkbox,radio和select,选中属性对应”checked”和”selected”,他们属于固有属性,应该使用prop方法去操作。

参考:http://www.cnblogs.com/tangge/p/5086235.html
参考:http://www.cnblogs.com/Showshare/p/different-between-attr-and-prop.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值