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

前端 未结 9 1846
清歌不尽
清歌不尽 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:54

    Rather try this.

    Add a common class to all Label's and fire event on that one. Like this :

    <ul>
        <li>
            <label for="test_0" class="testClass">
                <input id="test_0" name="offering_cycle" type="checkbox" value="1"> Fall
            </label>
        </li>
        <li>
            <label for="test_1" class="testClass">
                <input id="test_1" name="offering_cycle" type="checkbox" value="2"> Spring
            </label>
        </li>
        <li>
            <label for="test_2" class="testClass">
                <input id="test_2" name="offering_cycle" type="checkbox" value="3"> Summer
            </label>
        </li>
        <li>
            <label for="test_3" class="testClass">
                <input id="test_3" name="offering_cycle" type="checkbox" value="4"> Other
            </label>
        </li>
    </ul>
    

    And than,

    $(".testClass").on('click',function(){
          $(this).toggleClass('testing');
    });
    
    0 讨论(0)
  • 2020-12-20 17:56

    That's because you're binding event on label which contains checkbox and you're using for="chekbox_id". So, the event is fired for label as well as for checkbox.

    <ul>
        <li>
            <label for="test_0" class="">Fall</label>
            <input id="test_0" name="offering_cycle" type="checkbox" value="1" />
        </li>
        <li>
            <label for="test_1" class="">Spring</label>
            <input id="test_1" name="offering_cycle" type="checkbox" value="2" />
        </li>
        <li>
            <label for="test_2" class="">Summer</label>
            <input id="test_2" name="offering_cycle" type="checkbox" value="3" />
        </li>
        <li>
            <label for="test_3" class="">Other</label>
            <input id="test_3" name="offering_cycle" type="checkbox" value="4" />
        </li>
    </ul>
    <div id="target"></div>
    

    Take the input out of label.

    Demo: http://jsfiddle.net/tusharj/fdm1pmj2/5/

    0 讨论(0)
  • 2020-12-20 17:56

    Ok so what I said in the comment. It generates two click events, do this instead and it works like a charm: Fiddle

    $('input').on('click',function(){
       console.log("clicked");
        $('div#target').append($(this).parent().clone());    
    });
    

    You might want to rename your inputs.

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