Javascript Event Bubbling

后端 未结 2 558
时光说笑
时光说笑 2020-12-06 22:20

I have this setup

1 2 3
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 22:33

    In the event bubbling model, the event propagation is from the inner elements to the outer elements.

    This means that the event.stopPropagation(); should be in the inputs' events instead of the div.

    1 3

    Now the Javascript code:

    function stopPropagation() {
      //... do something.
      //stop propagation:
      if (!e) var e = window.event;
      e.cancelBubble = true; //IE
      if (e.stopPropagation) e.stopPropagation(); //other browsers
    }
    

    More info: http://www.quirksmode.org/js/events_order.html

    EDIT: The above was a quick way to show how the bubbling model works, but a better answer to solve this problem using JQuery would be:

    1 2 3

    Now the Javascript code:

    $('#mydiv').click(function(e) {
      //do something
    });
    
    $('#mydiv input').click(function(e) {
      //stop propagation:
      if (!e) var e = window.event;
      e.cancelBubble = true; //IE
      if (e.stopPropagation) e.stopPropagation(); //other browsers
    });
    

提交回复
热议问题