点击事件目标提供了元素或其子元素,而不是父元素 [英] Click event target gives element or it's child, not parent element

查看:61
本文介绍了点击事件目标提供了元素或其子元素,而不是父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个HTML元素:

I've got this HTML element:

<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>

这个Javascript:

And this Javascript:

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

          console.info(event.target)
        }
    }
}

问题是 event.target 返回我单击的确切元素.这意味着它可以是 a 元素,也可以是其子元素之一( h4 p ).

The problem is that event.target return the exact element I click. That means it can be the a element, or one of it's children (h4 or p).

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

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

推荐答案

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

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

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

这篇关于点击事件目标提供了元素或其子元素,而不是父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆