[英]Event delegation, Event.target vs Event.currentTarget
In MDN Event.target reference there is an example about implementing event delegation:在MDN Event.target 参考中有一个关于实现事件委托的例子:
// 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
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
How can margin on <li>
elements make difference between Event.target
and Event.currentTarget
? <li>
元素的边距如何在Event.target
和Event.currentTarget
之间产生差异?
Have in mind what makes event.target
different than event.currentTarget
as stated in MDN Event.currentTarget reference :请记住是什么使
event.target
与event.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.target
和event.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.