Why is the onClick event triggered twice?

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

I have the following html:


    
&         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 03:19

    Note that you have used jQuery's click method, it will emit both dom's mouse click event and jquery's click event. Then both jquery's click Event and dom's mouse click event are propagated to the span element and its onclick listener is triggered twice hence it alert twice

    check this demo to figure it out

    as for how to deal with it, just use stopPropagation as answers above

    $('#test1').click(function() {
    
      // comment this line and run, 'parent' will be alerted TWICE!!! since both mouseEvent and jQuery.Event trigger the onclick listener
      $('#children').click(function(e) {e.stopPropagation()})
    
    });
    

提交回复
热议问题