Javascript侦听器在事件目标的子对象而非实际元素上触发 [英] Javascript listener triggers on child of the event target, not the actual element

查看:48
本文介绍了Javascript侦听器在事件目标的子对象而非实际元素上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript事件处理程序,无法为我获取所需的属性.这是我的情况.

I have a Javascript event handler that is not getting me the attributes I need. Here is my situation.

我有一个类似于以下内容的HMTL DOM:

I have an HMTL DOM similar to the following:

<div id='section-header'>
    <a href="#anchor1">
        <img src="path/to/an/image1.png">
    </a>
    <a href="#anchor2">
        <img src="path/to/an/image2.png">
    </a>
</div>

我正在实例化事件监听器,如下所示:

I am instantiating my event listener like so:

var aList = document.getElementById('section-header').getElementsByTagName('a');

var anchorScroll = (event) => {
    event.preventDefault();

    var target = event.target.attributes;
    console.log("target: ", target);
};

for (var i = 0;i < aList.length;i++) {
    aList[i].addEventListener('click', anchorScroll, false);
}

当我单击其中一张图像时,将触发事件功能,但是目标元素是图像,而不是 a 标记.因此, attributes 对象没有 href 键-值对,因此我需要 href .相反,属性对象只有一个 src 键值对.

When I click on one of the images, the event function is fired, however the target element is the image, not the a tag. Thus, the attributes object does not have an href key-value pair, and I need that href. Instead, the attributes object only has an src key-value pair.

为什么 a 元素不是此事件的目标?我该如何补救?

Why is the a element not the target of this event? How do I remedy this?

推荐答案

是的,事件的初始目标是 img ,因为它是被单击的最里面的元素.为了区分它和事件处理程序实际绑定的元素, Event 对象具有 target currentTarget 属性:

Yes, the initial target of the event will be the img, since it's the innermost element that was clicked on. To distinguish between it and the element the event handler is actually bound to, the Event object has both target and currentTarget properties:

( currentTarget )[i]标识事件的当前目标,因为事件遍历DOM.它始终是指事件处理程序已附加到的元素,而不是 event.target ,后者标识发生事件的元素.

(currentTarget) [i]dentifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

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

或者您可以简单地使用 this .

Or you may simply use this instead.

这篇关于Javascript侦听器在事件目标的子对象而非实际元素上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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