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");
                    });
                }

            });
        });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM