简体   繁体   English

停止将事件从子元素转发到父元素

[英]Stop Event forwarding from children elements to parent

let's suppose to have following code: 让我们假设有以下代码:

<body style="overflow: hidden">
    <div class="wall">
        <button>New</button>
        <div class="prova">
            <a href="localhost">ciao !</a>
        </div>
       <div class="prova">
            <a href="localhost">miao !</a>
        </div>
    </div>
</body>

and the following js/jquery code: 以及以下js / jquery代码:

function onBoot()
{
    $(".prova").draggable();

    $(".wall").mousedown(onMouseDown);
    $(".wall").mouseup(onMouseUp);
}


function onMouseDown(e)
{
    console.log("down");
}

function onMouseUp(e)
{
    console.log("up");
}


$(onBoot);

Now, I correctly see the button and the two divs. 现在,我正确地看到了按钮和两个div。 When I click on "wall" (parent div) I see "down"/"up" on console as I expect. 当我单击“ wall”(父div)时,我在控制台上看到了“ down” /“ up”,这是我所期望的。 However, I see "down"/"up" on console also when I click on "prova" divs and button too. 但是,当我也单击“ prova” div和按钮时,在控制台上也看到“ down” /“ up”。 I know about "bubbling up" concept for which an event is forwarded from children to parent elements and I want to prevent it but without specifying an explicit event handler on "prova" divs. 我知道有关“冒泡”概念的信息,该事件将从子级转发到父元素,并且我想防止这种情况发生,但未在“ prova” div上指定显式事件处理程序。 Is it possible ? 可能吗 ?

You can check the originators className, like this: 您可以检查发起方的className,如下所示:

function onMouseDown(e)
{
  e = e || event;
  if ((e.srcElement || e.target).className === 'wall') {console.log("down");}
  return true;
}

see this jsfiddle 看到这个jsfiddle

In your event handler ( OnMouseDown , OnMouseUp ), check if e.currentTarget equals e.target . 在事件处理( OnMouseDownOnMouseUp ),检查是否e.currentTarget等于e.target See jQuery Events documentation : 请参阅jQuery Events文档

It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. 将event.target与此进行比较通常很有用,以确定是否由于事件冒泡而正在处理该事件。 This property is very useful in event delegation, when events bubble. 当事件冒泡时,此属性在事件委托中非常有用。

So, for example: 因此,例如:

function onMouseDown(e)
{
    if(e.currentTarget !== e.target)
        return;

    console.log("down");
}

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

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