简体   繁体   English

事件委托,Event.target vs Event.currentTarget

[英]Event delegation, Event.target vs Event.currentTarget

In MDN Event.target reference there is an example about implementing event delegation:MDN Event.target 参考中有一个关于实现事件委托的例子:

Event delegation example事件委托示例

// Assuming there is a 'list' variable containing an instance of an  
// HTML ul element.
function hide(e) {
    // Unless list items are separated by a margin, e.target should be  
    // different than e.currentTarget
    e.target.style.visibility = 'hidden';
}

list.addEventListener('click', hide, false);

// If some element (<li> element or a link within an <li> element for  
// instance) is clicked, it will disappear.
// It only requires a single listener to do that

Unclear part of the example例子中不清楚的部分

What i don't understand in the example is this comment:我在这个例子中不明白的是这个评论:

// Unless list items are separated by a margin, e.target should be  
// different than e.currentTarget

Question

How can margin on <li> elements make difference between Event.target and Event.currentTarget ? <li>元素的边距如何在Event.targetEvent.currentTarget之间产生差异?

Have in mind what makes event.target different than event.currentTarget as stated in MDN Event.currentTarget reference :请记住是什么使event.targetevent.currentTarget不同,如MDN Event.currentTarget 参考中所述

I think the point is that if there's no margin, then it'll be impossible to click directly on the ul since the li elements will entirely fill its space.我认为关键是如果没有边距,则无法直接单击ul因为li元素将完全填满其空间。

If there is a margin, then it'll at least be possible to click the ul , in which case event.target and event.currentTarget will be the same.如果余量,那么它至少会是可能的点击ul ,在这种情况下event.targetevent.currentTarget将是相同的。

 function hide(e) { document.querySelector("pre").textContent += 'e.target = ' + e.target.nodeName + ", e.currentTarget = " + e.currentTarget.nodeName + "\\n"; } document.querySelector("#list").addEventListener('click', hide, false);
 ul { border: 2px solid orange; } li { padding: 10px; color: blue; margin: 30px; border: 1px dashed blue; }
 <pre></pre> <ul id="list"> <li>click me <li>click me <li>click me </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM