只有event.target的目标父级? [英] Only target parent with event.target?

查看:111
本文介绍了只有event.target的目标父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<div onclick="doSomething()" id="parent">
    <div id="child"></div>
</div>

CSS:

#parent {
    background-color: blue;
    width: 100%;
    height: 100px;
}

#child {
    background-color: green;
    width: 50%;
    height: inherit;
}

.myClass {
    background-color: red !important;
}

JS:

function doSomething() {
    event.target.className = ('myClass');
}

正如你在此JSFIDDLE ,在单击子项时,不将该类应用于触发该函数的父项,而是将其应用于子项。我想知道如何避免这种情况并将其应用于父母,无论我在哪里点击它。我试图避免使用 document.getElement(s)ByClass / Id 方法。
任何帮助?

As you can see in this JSFIDDLE, upon clicking the child, instead of applying the class to the parent which triggers the function, it applies it to the child. I want to know how to avoid this and apply it to the parent no matter where I click inside of it. I am trying to avoid using the document.getElement(s)ByClass/Id method.
Any help?

推荐答案

您可以使用 currentTarget

You can refer to the element that handles the event with currentTarget.


当事件遍历DOM时,标识事件的当前目标。它始终引用事件处理程序附加到的元素,而不是 event.target ,它标识事件发生的元素。

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.






但是,不是依靠浏览器提供全局事件对象,我会将它传递给函数:


However, instead of relying on the browser to provide a global event object, I would pass it to the function:

onclick="doSomething(event)"

你也可以用这个来引用处理程序绑定的元素:

You can also refer to the element the handler is bound to with this:

onclick="doSomething(event, this)"

当然请考虑不使用内联事件处理程序

这篇关于只有event.target的目标父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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