How to stop event propagation when using delegate?

后端 未结 6 499
日久生厌
日久生厌 2021-01-18 05:12

When I use .bind to bind event on child and parent, child event can stop event propogation with return false; But when I use delegate, return false; does not stop event prop

相关标签:
6条回答
  • 2021-01-18 05:34

    e.stopPropagation() won't work in this case. Use e.stopImmediatePropagation() instead. Here's a fiddle

    0 讨论(0)
  • 2021-01-18 05:34

    your event is not being propagated. you are binding a click handler to the .parent, and you are clicking on .parent

    0 讨论(0)
  • 2021-01-18 05:38

    What worked for me was to check the class name of the click target in the click handler that you don't want to get triggered by other click event. Something like this.

        if(e.target.className.toString().indexOf("product-row") > -1){ 
          // Only do stuff if the correct element was clicked 
        }
    
    0 讨论(0)
  • 2021-01-18 05:39

    You should be using e.stopPropagation() to prevent the propagation, not by returning false.

    return false is technically two things; 1) prevent the default action, and 2) stop propagation. Try switching to the method invocation on e and see if that fixes your problem.

    0 讨论(0)
  • 2021-01-18 05:51

    You can always use e.stopPropagation()

    0 讨论(0)
  • 2021-01-18 05:53

    Why two click handlers when you can have one:

    $( '.parent' ).click(function ( e ) {
        if ( $( e.target ).is( '.child' ) ) {
            alert( 'child click' );
        } else {
            alert( 'parent click' );
        }    
    });
    

    Live demo: http://jsfiddle.net/J3EAQ/2/


    A generalization of this pattern:

    $( element ).click(function ( e ) {
        if ( e.target === this ) {
            // this element was clicked directly
        } else {
            // this element was NOT clicked directly
            // a descendant of this element was clicked
        }    
    });
    

    Separate handlers?

    $( '.parent' ).click(function ( e ) {
        if ( this ==== e.target ) {
            parentClicked.call( e.target, e );
        } else {
            childClicked.call( e.target, e );
        }    
    });
    
    function childClicked( e ) {
        // child click handler
    }
    
    function parentClicked( e ) {
        // parent click handler
    }
    
    0 讨论(0)
提交回复
热议问题