jquery操作单选框选中状态

原文:http://blog.csdn.net/jiegeng2233/article/details/53083545

jquery中同时提供了attr()与prop()方法对属性进行获取

栗子

<div class="cb-container">
<input type="radio" class="cb-radio" id="r1" name="rd" value="left"/>
<input type="radio" class="cb-radio cb-gap2" id="r2" name="rd" value="right"/>
<button id="btn" type="button" class="btn btn-primary cb-gap">left</button>
<button id="btn2" type="button" class="btn btn-primary cb-gap">right</button>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        var radios = $(".cb-radio");
        $("#btn").click(function () {
            radios.eq(0).attr("checked", true);
            radios.eq(1).attr("checked", false);
        });
        $("#btn2").click(function () {
            radios.eq(0).attr("checked", false);
            radios.eq(1).attr("checked", true);
        });
    });
</script>

整体代码可以在  https://example.codeboy.me/jquery/radio_operate_0.html  查看

测试后发现 left 与 right 按钮只有第一次点击后才能选择,之后点击后单选框的选中状态将一直处于未选中状态。

官网解释说:

在jquery1.6之后,对于checked,selected等进行状态改变时,需要使用的是prop()而不是attr(),于是我们我们将之前代码中的attr改变为prop后,可以看到运行效果如下,代码可以在 https://example.codeboy.me/jquery/radio_operate_1.html 查看。

<script type="text/javascript">
    $(document).ready(function () {
        var radios = $(".cb-radio");
        $("#btn").click(function () {
            radios.eq(0).prop("checked", true);
            radios.eq(1).prop("checked", false);
        });
        $("#btn2").click(function () {
            radios.eq(0).prop("checked", false);
            radios.eq(1).prop("checked", true);
        });
    });
</script>

//返回 true 或 false , 进而判断是哪个单选框被选中的。
$("#r1").prop();


猜你喜欢

转载自blog.csdn.net/xm_csdn/article/details/78432060