Click event triggering two times

前端 未结 5 661
终归单人心
终归单人心 2021-01-18 21:25


I am trying to run some function when clicking on the label text but the click event fired two times.
HTML

5条回答
  •  粉色の甜心
    2021-01-18 22:14

    I couldn't reproduce this in the version of chrome that I'm using.

    But if you're facing this in some browser, it's likely because -

    According to spec, labels containing inputs, and the ones connected to an input via for attribute trigger a click on the associated input when they are clicked.

    So in your first case, there are 2 click events:

    • Actual click on
    • Click triggered on by the label

    The one triggered on will bubble up to and trigger your handler.

    In the second case, Since a for attribute is specified and there is no matching input with id of 'test', the additional click is not triggered even if the input is inside the label.

提交回复
热议问题