Javascript click event triggers twice

前端 未结 3 790
时光取名叫无心
时光取名叫无心 2021-01-04 09:30

In the following snippet, why does divClicked() trigger twice when the is clicked, but only once wh

3条回答
  •  梦毁少年i
    2021-01-04 09:57

    This is usually be cause of the bubbling principle of click event:

    When an event happens on an element, it runs on it, its associated elements,its parent and other ancestors.

    Now, The relation is when you click on label there a are two events which bubbles up here:

    1) Click on div (which you expect)

    2) Click on input (which is also expected)

    2.1) When click on input is triggered then a click on div is also triggered again here

    You can confirm this behavior by using event.bubbles prop.

    EDIT:

    The reason for the connection between label and input: (I know this is absolutely not required, as it's present all over the place yet)

    A can be associated with a control either by placing the control element inside the element, or by using the for attribute. Such a control is called the labeled control of the label element. One input can be associated with multiple labels.

    Taken from: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

    Which means placing for on label referencing id of an input element will stimulate the behavior as if the element is inside the label. This would bubble a event on input onto label like any event on child to parent

提交回复
热议问题