jquery中單選選中及清除選中狀態
阿新 • • 發佈:2018-02-23
func gpo bsp sort att nbsp class one inpu
不管是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"); }); } }); });
jquery中單選選中及清除選中狀態