dramasea dramasea - 10 months ago 65
HTML Question

Why the onclick element will trigger twice for label element

window.onload = function(){
var wow = document.getElementById("wow");
wow.onclick = function(){

<label id="wow"><input type="checkbox" name="checkbox" value="value">Text</label>

This is my code, when I clicked on "Text" it will alert hi twice but when I clicked on the box, the
element will only trigger once, why?


When you click on the label, it triggers the click handler, and you get an alert.

But clicking on a label also automatically sends a click event to the associated input element, so this is treated as a click on the checkbox. Then event bubbling causes that click event to be triggered on the containing element, which is the label, so your handler is run again.

If you change your HTML to this, you won't get the double alert:

<input id="wowcb" type="checkbox" name="checkbox" value="value">
<label id="wow" for="wowcb">Text</label>

The label is now associated with the checkbox using the for attribute instead of wrapping around it.