利用jQuery動態設置單選框的選中


一、需要實現的效果

這里使用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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM