Why is the onClick event triggered twice?

前端 未结 10 1242
夕颜
夕颜 2021-02-05 02:40

I have the following html:


    
&         


        
相关标签:
10条回答
  • 2021-02-05 02:59

    Here button click is triggered. Since the button is inside the span and onclick event is defined for span the two alert are happened.

    One is by the button 
    

    and

    other by its parent(parent have onclick event and button click is triggered).

    To avoid two alert, use this

    <span>
        <button onclick="alert('Boem')" id="test1">test</button>
    </span>
    
    0 讨论(0)
  • 2021-02-05 02:59

    I also face this problem on Modal

    Solved by the following tricks -

    $('#saveButton').off('click').on('click', { modal: modal }, save)
    

    Here off('click') prevents the save method fires multiple times.

    0 讨论(0)
  • 2021-02-05 03:00

    It is calling twice because button is inside a span and span has onclick="alert('Boem')", hence when you trigger click on button then it shows alert and same click event propagate to span and shows alert once again.

    you need to stop default behaviour of button using below code :

    $(function(){
    $('#test1').click(function(e){e.preventDefault();}).click();
    });
    

    Demo

    0 讨论(0)
  • 2021-02-05 03:04

    Bubbling. The click event on the child also happens on the parent (span).

    0 讨论(0)
  • 2021-02-05 03:04

    I had the same problem. Mine was the fact that I was using .trigger('.element') and there were two elements with that element class.

    So, I got more specific, and used .trigger('.parent .element') to ensure only one click event happened on a single element, instead of one click event on two elements.

    0 讨论(0)
  • 2021-02-05 03:09

    I was also getting a similar issue where I had to download a pdf which was downloading twice. I used jQuery's stopImmediatePropagation method.

    $( "#test1" ).on("click", function(e) {
         e.stopImmediatePropagation();
    });
    
    $('#test1').trigger('click');
    

    stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing. Refer here for more details.

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