开发者

How to stop event propagation when using delegate?

开发者 https://www.devze.com 2023-04-05 05:06 出处:网络
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 propagation.

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 propagation.

http://jsfiddle.net/J3EAQ/

html:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>

js:

$('.parent').delegate('.child','click',function(e){
    alert('child click');
    ret开发者_JAVA技巧urn false;
});
$('.parent').bind('click',function(e){
    alert('parent click');
});


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


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
}


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.


You can always use e.stopPropagation()


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 
    }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号