首页 > 解决方案 > 单击事件目标给出元素或其子元素,而不是父元素

问题描述

我有这个 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>

而这个Javascript:

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

          console.info(event.target)
        }
    }
}

问题是event.target返回我点击的确切元素。这意味着它可以是a元素,也可以是其中一个子元素(h4p)。

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

标签: javascriptvue.jsvuejs2

解决方案


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

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


推荐阅读