代码
<!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次;
原因是label标签导致的,需要将onclick事件绑定或放到label包括的元素内。修改成如下
最终代码如下:
<!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>