码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-02-23 17:20:27      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:box   type   one   log   多选   check   ==   col   属性   

不管是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中单选选中及清除选中状态

标签:box   type   one   log   多选   check   ==   col   属性   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!