jQuery stopPropagation bubble down

前端 未结 2 1295
旧时难觅i
旧时难觅i 2020-11-29 04:10

I have a div with a link inside of it:

Lol

Clickin

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 04:38

    Events only bubble up. So the click event handler for the a element is fired before the click event handler for the div. If you want the behaviour you describe, the you need to add a click event handler to the a element which stops propagation to the div.

    $("#myDiv a").click( function(event) {
        event.stopPropagation();
    } );
    

    and keep whatever event handler you have on the div. This should allow the event to perform it's default action, and prevent the handler on the div being fired.

    If you only want to prevent clicks on links then you can change your event handler for the div element

    $("#myDiv").click( function( event ) {
        if( !$( event.target ).is( "a" ) )
        {
            // existing event handler
        }
    } );
    

提交回复
热议问题