Click事件目标给出元素或它的子元素,而不是父元素

时间:2018-05-03 08:04:19

标签: javascript vue.js vuejs2

我有这个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处理程序的元素)?

2 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:0)

CSS的替代解决方案:

a * {
    pointer-events: none;
}
  

该元素永远不会是指针事件的目标;但是,指针   如果事件的后代具有   指针事件设置为其他值。在这种情况下   指针事件将触发此父元素上的事件侦听器,如下所示:   在活动期间适合去往/离开后代的方式   捕获/气泡阶段。

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