onclick事件執行2次

代碼javascript

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>教程</title> </head> <body>

<p>測試label標籤致使onclick觸發2次</p> <p id="demo"></p>

<form> 
<ul> <li onclick="fun\_1('male')" > <label for="male">Male</label> <input type="radio" value="0" name="sex" id="male" /> </li> 		<li onclick="fun\_1('female')"> <label for="female">Female</label> <input type="radio" value="1" name="sex" id="female" /> 		</li> 
</ul>
</form>

<script src="[https://code.jquery.com/jquery-3.1.1.min.js](https://code.jquery.com/jquery-3.1.1.min.js)"></script> 
<script type="text/javascript">
function fun_1(id){
	alert($("#"+id).val());
}
</script>

</body> </html>

每次點擊都會彈窗2次;html

緣由是label標籤致使的,須要將onclick事件綁定或放到label包括的元素內。修改爲以下
java

最終代碼以下:jquery

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>教程</title> </head> <body>

<p>測試label標籤致使onclick觸發2次</p> <p id="demo"></p>

<form> 
<ul> 
	<li > <label for="male">Male</label> <input type="radio" onclick="fun\_1('male')" value="0" name="sex" id="male" /> </li> 	  <li> <label for="female">Female</label> <input type="radio" onclick="fun\_1('female')" value="1" name="sex" id="female" /> 	 </li>
</ul>
</form>
<script src="[https://code.jquery.com/jquery-3.1.1.min.js](https://code.jquery.com/jquery-3.1.1.min.js)"></script> 
<script type="text/javascript">
	function fun_1(id){
		alert($("#"+id).val());
	}
</script>

</body>
</html>
相關文章
相關標籤/搜索