仅以 event.target 为目标 parent?

Only target parent with 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');
}

正如您在 this JSFIDDLE 中看到的那样,单击 child 后,它不会将 class 应用于触发该功能的 parent,而是将其应用于child。我想知道如何避免这种情况并将其应用于 parent 无论我在其中单击什么位置。我试图避免使用 document.getElement(s)ByClass/Id 方法。
有什么帮助吗?

可以参考currentTarget处理事件的元素。

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.


但是,我不会依赖浏览器提供全局 event 对象,而是将其传递给函数:

onclick="doSomething(event)"

您还可以使用 this:

来引用处理程序绑定到的元素
onclick="doSomething(event, this)"

当然请考虑not use inline event handlers

只需在您的 javascript 调用中引用 target

function doSomething(target) {
 target.className = ('myClass');
}
#parent {
    background-color: blue;
    width: 100%;
    height: 100px;
}

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

.myClass {
    background-color: red !important;
}
<div onclick="doSomething(this)" id="parent">
    <div id="child"></div>
</div>

要获取被单击元素的直接父元素,您可以使用事件的 'path' 数组。 Path 提供了一个数组,其中包含从您单击的元素到 DOM 顶部按升序排列的每个元素。

虽然无法确定浏览器对此的确切支持。

var children = document.querySelectorAll('[id^="child-"]'),
  clickEvent = function(event) {
    console.log(event.path[0]); //prints clicked child element
    console.log(event.path[1]); //prints parent

    event.path[1].classList.toggle('row'); //toggles row or column mode of parent
    event.path[0].classList.toggle('selected'); //toggles color of child
  };

children.forEach(function(child) {
  child.addEventListener('click', clickEvent);
});
<div id="parent">
  <div id="child-1">Child One</div>
  <div id="child-2">Child Two</div>
  <div id="child-3">Child Three</div>
  <div id="child-4">Child Four</div>
  <div id="child-5">Child Five</div>
</div>