How to stop event propagation when using delegate?

后端 未结 6 539
日久生厌
日久生厌 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: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
    }
    

提交回复
热议问题