Event:target 屬性
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
備註: 此功能可在 Web Worker 中使用。
Event 介面的 target 唯讀屬性是對事件被派發到的物件之參照。當事件處理器在事件的冒泡或捕獲階段被呼叫時,它與 Event.currentTarget 不同。
值
相關聯的 EventTarget。
範例
event.target 屬性可用於實作事件委派。
js
// 建立一個列表
const ul = document.createElement("ul");
document.body.appendChild(ul);
const li1 = document.createElement("li");
const li2 = document.createElement("li");
ul.appendChild(li1);
ul.appendChild(li2);
function hide(evt) {
// evt.target 指的是被點擊的 <li> 元素
// 這與 evt.currentTarget 不同,在此上下文中的 currentTarget 指的是父層 <ul>
evt.target.style.visibility = "hidden";
}
// 將監聽器附加到列表
// 當每個 <li> 被點擊時,它都會觸發
ul.addEventListener("click", hide);
規範
| Specification |
|---|
| DOM> # ref-for-dom-event-target③> |