简体   繁体   English

stopPropagation 不适用于嵌套的 href 标签

[英]stopPropagation not working with nested href tag

I have multiple divs listed like so:我有多个 div,如下所示:

<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.我试图捕捉父 div 的点击事件,但是当点击 href 元素时,我的点击事件也被触发,而不是仅仅跟随点击的链接。

Here is my jquery call:这是我的 jquery 调用:

//$(".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 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).与任何其他事件一样,单击事件使用冒泡 ( http://en.wikipedia.org/wiki/DOM_events ) 分派给元素,因此单击的任何内部元素都将触发所有父元素(另一种方式称为隧道)。

You have to put the stopPropagation on the anchor element onclick event or put in the element:您必须将 stopPropagation 放在锚元素 onclick 事件上或放入元素:

onclick="return false;"

To enable the link inside the div, use this JavaScript.要启用 div 内的链接,请使用此 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.添加e.preventDefault()解决了这个问题。 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.此外,将其添加到其子项的<a>也没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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