zoukankan      html  css  js  c++  java
  • 利用jQuery动态设置单选框的选中

    一、需要实现的效果

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

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title>动态设置单选框的选中</title>
    		<!--
            	作者:Harrison
            	时间:2018-12-05
            	描述:当下拉条改变时,动态的设置单选框的值
            -->
    	</head>
    	<body>
    		<select id="sexSelect" style=" 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");
  • 相关阅读:
    javascript实现图片的淡入淡出
    javascript实现(分享到xxx)的小实例
    javascript中奇怪事件
    javascript方式实现无缝滚动(两种方式)
    jquery 函数的3种用法
    jquery方法的隔行变色
    DOM对象与jquery对象
    入口函数的标准
    真数组与伪数组的区别
    创建正则表达式对象
  • 原文地址:https://www.cnblogs.com/helf/p/10074268.html
Copyright © 2011-2022 走看看