当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 使用jQuery动态设置单选框的选中效果

使用jQuery动态设置单选框的选中效果

2019年06月01日  | 移动技术网IT编程  | 我要评论

一、需要实现的效果

这里使用jquery来实现。需要实现的效果如下:当下拉条改变时,单选框选中的值随之变化。

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>动态设置单选框的选中</title>
    <!--
      作者:harrison
      时间:2018-12-05
      描述:当下拉条改变时,动态的设置单选框的值
    -->
  </head>
  <body>
    <select id="sexselect" style="width: 10%;">
      <option value="1">男</option>
      <option value="2">女</option>
    </select>
    男:<input type="radio" value="1" name="sex" id="sexradio1" checked/>
    女:<input type="radio" value="2" name="sex" id="sexradio2"/>
  </body>
  <script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
  <script type="text/javascript">
    $("#sexselect").change(function(){
      //获取选中的下拉条
      var checkedofselect = $("#sexselect").val();
      //动态设置单选框的选中
      if(checkedofselect == 1){
        $("#sexradio1").prop("checked",true);
        $("#sexradio2").prop("checked",false);
      }
      if(checkedofselect == 2){
        $("#sexradio1").prop("checked",false);
        $("#sexradio2").prop("checked",true);
      }
    });
  </script>
</html>

二、注意

•当设置单选框的checked属性时,要使用jquery的prop()方法,不能够使用jquery的attr()方法,attr()只适合简单html元素设置。
•jquery的prop()方法,第二个参数为布尔值,不能设置成string类型:

  正确:$("#sexradio1").prop("checked",true);
  错误:$("#sexradio1").prop("checked","true");

总结

以上所述是小编给大家介绍的使用jquery动态设置单选框的选中效果,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网