使用 jQuery 实现 radio 的选中与反选

使用 jQuery 实现 radio 的选中与反选

我们知道在 Html 中当我们选中一个radio后,再次点击该 radio,那么该 radio 依然是一个选中的状态,但是有时我们需要实现这样的逻辑:一个选中的 radio,再次点击该 radio 时,会取消它的选中状态 。

演示效果

实现逻辑

  • 取消 click 事件的默认动作
  • 使用 mouseup 控制 radio 的选中与反选
<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
        <script type="text/javascript">

            $(function(){

                $(":radio[name='sex']").click(function(event){
                    // 禁用事件的默认动作
                    event.preventDefault();
                })
                // 绑定一个鼠标单击事件
                .mouseup(function(){
                    $(this).prop("checked",!$(this).is(":checked"));
                });
            })
        </script>
  </head>
  <body>
    男:<input type="radio" name="sex" value="1"> 女:<input type="radio" name="sex" value="0">
 </body>
</html>

此文参考至:https://www.cnblogs.com/zz-930474270/p/7091147.html


posted @ 2017-11-28 16:30  Duke-码动青春  阅读(900)  评论(0编辑  收藏  举报