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

编程入门 行业动态 更新时间:2024-10-28 04:25:32
本文介绍了单击事件目标给出元素或其子元素,而不是父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

更多推荐

[db:关键词]

本文发布于:2023-03-31 10:16:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/801391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   单击   其子   而不是   目标

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!