Why are two click events registered in this html/css/jquery

前端 未结 9 1851
清歌不尽
清歌不尽 2020-12-20 17:25

I am trying to style a checkbox list. I\'ve added my styles and they appear correctly when rendered. I want to add a class when the label for the checkbox is clicked. This i

9条回答
  •  执念已碎
    2020-12-20 17:32

    To explain what happens:

    • Input is clicked, but since the LABEL is bound to that Input using for attribute and for simply being it's child element, here's your first registered event.
    • Than the input propagates the click (all elements propagate clicks) down to LABEL, and since the label is your delegated element - here's your second event being triggered.

    Since you wrapped your Input Checkboxes inside a LABEL element,
    you can actually listen the even on the input:

    $('label[for*=test_] input').on('click',function(){
        $('div#target').append($(this).closest("label").clone());    
    });
    

    and than clone the parent label. jsFiddle


    Another way to prevent those brotherhood between LABEL and the inner INPUT is to stop the input to propagate the event letting the bounding label>>checkbox to it's job: fiddle

    $("label:input").on("click", function( evt ) {
        evt.stopPropagation();
    });
    $('label[for*=test_]').on('click',function(){
        $('div#target').append($(this).clone());
    });
    

    Otherwise you could prevent the default LABEL's behavior jsFiddle
    that triggers back events from the bound INPUT and that's using e.preventDefault() but your (hidden) input checkbox will not get checked!

    $('label[for*=test_]').on('click',function( e ){
        e.preventDefault();
        $('div#target').append($(this).clone()); 
    });
    

    https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

提交回复
热议问题