jquery单选框redio设置checked属性无效的原因

jquery设置标签本身的属性使用prop(),设置自定义属性使用attr()。

下面用例:点击选中复选框,默认选择单选框的“是”,取消复选框之后,取消单选框的选择。

<div style="border:1px solid #ddd;padding-bottom: 20px;">
    <h5>jquery控制,</h5>
    <small style="display: block;">当复选框选中时,默认选中auth中的‘是’,复选框不选中,单选框全部不选中</small>

    <label><input type="checkbox" name="aa" class="btn1"> 点击我</label>
    <br>
    <label><input type="radio" name="auth" value="1"></label>
    <label><input type="radio" name="auth" value="0"></label>
</div>
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.0.0/jquery.min.js"></script>
<!-- <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> -->
<script>
    $(".btn1").click(function () {
     
     
        if (this.checked) {
     
     
            //选中 auth值为1的单选框
            $("input[name='auth']").each(function () {
     
     
                if ($(this).val() === '1') {
     
     
                    // 1. 高版本jquery
                    // $(this).attr('checked', true);

                    //2.高版本jquery和低版本
                    $(this).prop('checked', true);

                    //3.原生js
                    // this.checked = true;
                }
            });
        } else {
     
     
            //取消auth所有选中的值
            $("input[name='auth']").each(function () {
     
     
                // 1.高版本jquery
                // $(this).attr('checked', false);

                //2.高版本jquery和低版本
                $(this).prop('checked', false);

                //3.原生js
                // this.checked = false;
            });
        }
    });
</script>

猜你喜欢

转载自blog.csdn.net/kouzuhuai2956/article/details/113178077