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

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

问题描述

我有这个 HTML 元素:

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

还有这个 Javascript:

返回新的 Vue({方法: {showDetails:函数(通知,事件){this.notification = 通知控制台信息(事件.目标)}}}

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

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

解决方案

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

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

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>

And this Javascript:

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

          console.info(event.target)
        }
    }
}

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

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

解决方案

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/en-US/docs/Web/API/Event/currentTarget

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

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