复选框checkbox单选效果

先引入jQuery

[注意jQuery版本]

实现此功能的主要原理:
通过is(':checked ')判断当前对象是否被选中,对已选中的对象及同胞元素的属性进行设置

HTML:

<div class="judge-box">
                        <span>是否为物业公司 :</span>
                        <label>是</label>
                        <input id="check-area1" type="checkbox" name="checkBox" value="是">
                        <label class="judge-box-no">否</label>
                        <input id="check-area2" type="checkbox" name="checkBox" value="否">
</div>

JS:

$(document).ready(function(){
      $("input[name='checkBox']:checkbox").click(function(){
            if($(this).is(':checked')){
                $(this).attr('checked',true).siblings().attr('checked',false);
            }else{
                $(this).attr('checked',false).siblings().attr('checked',false);
            }
             str = $(this).attr("value");
            // console.log(str)获取并且打印选中项---   是 / 否
        });
})

因为有的需要加样式,使得lable不在同级,所以方法有局限

刚刚又总结出了一种比较low的方法,

<div class="widthDraw-area">
            <div class="checkArea area-top">
                <span>提现到微信红包</span>
                <section>
                    <div class="checkbox-area">
                        <input type="checkbox" value="1" id="checkboxInputOne" name="checkBoxJudge" checked/>
                        <label for="checkboxInputOne"></label>
                    </div>
                </section>
            </div>
            <div class="checkArea area-bottom">
                <span>提现到银行卡</span>
                <section>
                    <div class="checkbox-area">
                        <input type="checkbox" value="2" id="checkboxInputTwo" name="checkBoxJudge"/>
                        <label for="checkboxInputTwo"></label>
                    </div>
                </section>
            </div>
        </div>

 比如现在我的lable不在同级,这时可以用jQuery分情况判断处理。

$(document).ready(function () {//单选
        $("input[name='checkBoxJudge']:checkbox").click(function(){
            if($(this).is(':checked')){
                //console.log($(this).attr('id'))
                if($(this).attr('id') === 'checkboxInputOne'){
                    $('#checkboxInputTwo').attr('checked',false);
                    $('#checkboxInputOne').attr('checked',true);
                }else{
                    $('#checkboxInputTwo').attr('checked',true);
                    $('#checkboxInputOne').attr('checked',false);
                }
            }else{
                $('#checkboxInputTwo').attr('checked',false);
                $('#checkboxInputOne').attr('checked',false);
            }
        });
    });

 这里我获取了元素id去进行判断处理,以后有更好方法了再来分享总结

猜你喜欢

转载自570109268.iteye.com/blog/2388068