开发者

jQuery stopPropagation bubble down

开发者 https://www.devze.com 2022-12-28 16:21 出处:网络
I have a div with开发者_如何学运维 a link inside of it: <div id=\"myDiv\"> <a href=\"http://www.lol.com\">Lol</a>

I have a div with开发者_如何学运维 a link inside of it:

<div id="myDiv">
    <a href="http://www.lol.com">Lol</a>
</div>

Clicking the <div /> should go somewhere, but clicking the child <a /> should go to www.lol.com. I've seen from previous questions and the jQuery website that .stopPropagation prevents bubbling upwards, but how do I prevent a bubble downwards (isn't that what's necessary here?).


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
    }
} );


The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

Checking in the DIV click event handler whether the actual target element was the anchor → jsFiddle

$('#myDiv').click(function (evt) {
    if (evt.target.tagName != "A") {
        alert('123');
    }

    // Also possible if conditions:
    // - evt.target.id != "ancherComplaint"
    // - !$(evt.target).is("#ancherComplaint")
});

$("#ancherComplaint").click(function () {
    alert($(this).attr("id"));
});

Stopping the event propagation from the anchor click listener → jsFiddle

$("#ancherComplaint").click(function (evt) {
    evt.stopPropagation();
    alert($(this).attr("id"));
});

As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

0

精彩评论

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

关注公众号