jquery中单选选中及清除选中状态

不管是checkbox(多选)还是radio(单选) 添加checked属性时候建议用prop而不用attr

单选用attr点击一次添加checked="checked"属性,点击第二次页面上才显示选中状态

多选用attr只有第一次点击有效,其余的不会标识为选中状态

 ////1、单选示例

//html代码      
<ul>
                    <li class="li_check">
                        <input class="check_box" checked="checked" type="radio" name="sort" value="1" id="sort_one" /><label for="sort_one">1</label>
                    </li>
                    <li class="li_check">
                        <input class="check_box" type="radio" name="sort" value="2" id="sort_two" /><label for="sort_two">2</label></li>
                    <li class="li_check">
                        <input class="check_box" type="radio" name="sort" value="3" id="sort_three" /><label for="sort_three">3</label></li>                
                </ul>
//js代码
 $(".check_box").click(function () {
            if ($(this).prop("checked") != "checked")
            {
                $(".check_box").each(function () {
                    $(this).removeAttr("checked");
                });
                $(this).prop("checked", "checked");
            }

        });

///2、多选示例

//html代码
<span class="check-all">全选</span>
<ul> <li class="li_check"> <input class="check_box" checked="checked" type="checkbox" name="sort" value="1" id="sort_one" /><label for="sort_one">1</label> </li> <li class="li_check"> <input class="check_box" type="checkbox" name="sort" value="2" id="sort_two" /><label for="sort_two">2</label></li> <li class="li_check"> <input class="check_box" type="checkbox" name="sort" value="3" id="sort_three" /><label for="sort_three">3</label></li> </ul>
//js代码
  $(".check_box").click(function () {
            if ($(this).attr("checked") == "checked") {
                $(this).removeAttr("checked", "checked");
            }
            else {
                $(this).attr("checked", "checked");
            }
        });
       
        $(function () {
            var click = 0;
            $(".check-all").click(function () {
                click = click + 1;
                if (click % 2 == 1) {
                    $(".check_box").prop("checked", "checked");
                    $(".check_box").each(function () {
                        $(this).attr("checked", "checked");
                    });
                }
                else {
                    $(".check_box").removeAttr("checked", "checked");
                    $(".check_box").each(function () {
                        $(this).removeAttr("checked", "checked");
                    });
                }

            });
        });
原文地址:https://www.cnblogs.com/KnowEditByW/p/8462463.html