Click event triggering two times

前端 未结 5 660
终归单人心
终归单人心 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.

    0 讨论(0)
  • 2021-01-18 22:13
    <label for="text" class="label_one">
        Label One
        <input type="checkbox"/>
    </label>
    <br/><br/>
    <label for="text" class="label_two">
        Label Two
        <input type="checkbox" name="1"/>
    </label>
    

    you forgot to put for attribute in label (label_one). just change that. it will work

    0 讨论(0)
  • 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 <label>
    • Click triggered on <input> by the label

    The one triggered on <input> will bubble up to <label> 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.

    0 讨论(0)
  • 2021-01-18 22:18

    Click on checkbox do click on label. Try use .change event on input

    $('.label_one input').change(function(){
        var html = '<div class="log_sec_one">Log</div>';
        $('.logs').append(html);
    });
    
    $('.label_two input').change(function(){
        var html = '<div class="log_sec_two">Log</div>';
        $('.logs').append(html);
    });
    

    DEMO

    0 讨论(0)
  • 2021-01-18 22:21

    Move your input outside of your label, and use the for="" attribute.

    <label class="label_one" for="checkbox_one">
        Label One
    </label>
    <input type="checkbox" id="checkbox_one" />
    <br/><br/>
    <label for="checkbox_two" class="label_two">
        Label Two
    </label>
    <input type="checkbox" id="checkbox_two"/>
    
    <div class="logs"></div>
    

    JSFiddle: https://jsfiddle.net/hvv6ucu8/2/

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