javascript 单击事件目标给出元素或其子元素,而不是父元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50149925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:56:39  来源:igfitidea点击:

Click event target gives element or it's child, not parent element

javascriptvue.jsvuejs2

提问by Stephan Vierkant

I've got this HTML element:

我有这个 HTML 元素:

<div class="list-group">
    <a href="javascript:;" @click="showDetails(notification, $event)" class="list-group-item" v-for="notification in notifications" :key="notification.id">
        <h4 class="list-group-item-heading">{{ '{{ notification.title }}' }}</h4>
        <p class="list-group-item-text">{{ '{{ notification.created_at|moment }}' }}</p>
    </a>
</div>

And this Javascript:

而这个 Javascript:

return new Vue({
    methods: {
        showDetails: function (notification, event) {
          this.notification = notification

          console.info(event.target)
        }
    }
}

The problem is that event.targetreturn the exact element I click. That means it can be the aelement, or one of it's children (h4or p).

问题是event.target返回我单击的确切元素。这意味着它可以是a元素,或者它的子元素之一(h4p)。

How do I get the aelement (the element with the @clickhandler), even if the user clicks on one of it's children?

即使用户单击其中一个子a元素,我如何获取元素(带有@click处理程序的元素)?

回答by ibrahim tanyalcin

use event.currentTargetwhich points to the element that you attached the listener. It does not change as the event bubbles

使用event.currentTarget指向您附加侦听器的元素。它不会随着事件冒泡而改变

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

回答by Itang Sanjana

Alternative solution with CSS:

使用 CSS 的替代解决方案:

a * {
    pointer-events: none;
}

The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

元素永远不是指针事件的目标;但是,如果这些后代将指针事件设置为其他值,则指针事件可能会针对其后代元素。在这些情况下,指针事件将在事件捕获/冒泡阶段期间,在它们往返后代的途中适当地触发此父元素上的事件侦听器。

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events#Values

参考:https: //developer.mozilla.org/en-US/docs/Web/CSS/pointer-events#Values