onclick事件執行2次
程式碼
`
<!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"></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"></script>
<script type="text/javascript"> function fun_1(id){ alert($("#"+id).val()); } </script>
</body> </html>