Click event triggering two times

前端 未结 5 719
终归单人心
终归单人心 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:01

    It is because of event bubbling.

    In general all elements bubble the event to the root of the document whereas the label tag will bubble the event to its child nodes and thats how the input tag is getting ticked when you click the label dom.

    So in your case you attached the event handler to label tag so

    1. It calls when label tag gets clicked
    2. event bubbles inside it and checkbox gets selected and checkbox bubbles the event to its parent node that is label tag again hence it is called twice.

    To solve this, just attach the event handler to input/checkbox tag it should work fine.

提交回复
热议问题