简体   繁体   中英

stopPropagation not working with nested href tag

I have multiple divs listed like so:

<div class="msg-list clearfix" id="27705">
  <div class="thumbnail_image">
    <a href="some_path">AnchorText</a>
  </div>
  <div class="msg-date">DATA</div>
</div>

I've trying to catch a click event for the parent div but when clicking the href element my click event is also getting triggered instead of just following the link clicked.

Here is my jquery call:

//$(".msg-list a").click(function(e) {
$(".msg-list").click(function(e) {

    e.stopPropagation(); 
    alert("Handler for .click() called.");
});

Any idea what I'm missing?

Try:

$(".msg-list").on('click', function(e) {
    alert("div handler");
    return false;
});
$(".msg-list a").on('click', function(e) {
    alert("a handler");
    e.stopPropagation();
});

Is this what you want? http://jsfiddle.net/L5kC4/2

The click event, like any other event is dispatched to the elements using Bubbling ( http://en.wikipedia.org/wiki/DOM_events ) so any inner element clicked will trigger all the parent elements (the other way is called Tunnelling).

You have to put the stopPropagation on the anchor element onclick event or put in the element:

onclick="return false;"

To enable the link inside the div, use this JavaScript. You have to disable Propagation on the contained element, the link!

$(".msg-list a").click(function(e) {
    e.stopPropagation();
});
$(".msg-list").on('click', function(e) {
    alert("Handler for .click() called.");
});

Old question. But, I had the same problem.

Adding e.preventDefault() fixed the problem. The default is to follow the link. So, preventing it from following.

Also, there's no problem adding that to the <a> of its children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM