簡體   English   中英

只有event.target的目標父級?

[英]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');
}

正如您在此JSFIDDLE中所看到的,在單擊子項時,不是將該類應用於觸發該函數的父項,而是將其應用於子項。 我想知道如何避免這種情況並將其應用於父母,無論我在哪里點擊它。 我試圖避免使用document.getElement(s)ByClass/Id方法。
有幫助嗎?

您可以使用currentTarget引用處理事件的元素。

當事件遍歷DOM時,標識事件的當前目標。 它始終引用事件處理程序附加到的元素,而不是event.target ,它標識事件發生的元素。


但是,我不會依賴瀏覽器來提供全局event對象,而是將其傳遞給函數:

onclick="doSomething(event)"

您也可以參照處理程序綁定到該元素this

onclick="doSomething(event, this)"

當然請考慮不使用內聯事件處理程序

如果您使用的addEventListener來處理該事件,而不是在線版本,那么this回調將指向該事件被宣布(#parent)的元素- 小提琴

<div id="parent">
    <div id="child"></div>
</div>

將此代碼放在正文的末尾或DOMContentLoaded事件處理程序中:

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

document.getElementById('parent').addEventListener('click', doSomething);

只需在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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM