Javascript click event triggers twice

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

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

相关标签:
3条回答
  • 2021-01-04 09:43

    At some moments, check also if the javascript file asset isn't loaded twice .... it shouldn't happen, but you never know.

    0 讨论(0)
  • 2021-01-04 09:46

    This happens because of what the HTML spec describes at 4.10.4:

    For example, on platforms where clicking a checkbox label checks the checkbox, clicking the label in the following snippet could trigger the user agent to run synthetic click activation steps on the input element, as if the element itself had been triggered by the user:

    <label><input type=checkbox name=lost> Lost</label>
    

    On other platforms, the behavior might be just to focus the control, or do nothing.

    This means that when a <label> is clicked, the browser creates a second "synthetic" click event on the associated <input> element, in order to toggle its state.

    The reason divClicked is triggered twice, is because the first event which comes from the <label> bubbles up to the <div>, and also the second, synthetic click event bubbles up to the <div>.

    0 讨论(0)
  • 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 <label> can be associated with a control either by placing the control element inside the <label> 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

    0 讨论(0)
提交回复
热议问题