为什么将元素与此关键字进行比较?
我正在查看以下 href =“ https://javascript.info/event-delegation” rel =“ nofollow noreferrer”>文档。
在链接中,我们有“关注”
let table = document.getElementById('bagua-table');
let selectedTd;
table.onclick = function(event) {
let target = event.target;
while (target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
}
target = target.parentNode;
}
}
我只是无法理解为什么以下while(target!= this)
。我了解此
在这里涉及整个表,因为那是在玩游戏的对象,但是为什么要以这种方式编写循环?
也许我对此的理解不是那么深。如果有人可以澄清。
谢谢
I am looking at the following link which is a part of event delegation documentation.
In the link, we have the followig
let table = document.getElementById('bagua-table');
let selectedTd;
table.onclick = function(event) {
let target = event.target;
while (target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
}
target = target.parentNode;
}
}
I am just unable to understand why the following while (target != this)
. I understand that the this
keyword here refers to the entire table since that is the object in play but why write a loop in this manner?
Maybe my understanding of this is not as deep. If someone could please clarify.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样做的是,
target
从事件的目标开始 - 该事件被派往的最内向元素。然后它搜索目标,然后是其祖先,然后是其祖先等等。第一个与条件target.tagname =='td'
(如果有)匹配的第一个将导致调用突出显示
。如果没有元素匹配,则循环将继续进行,直到目标为 - 表格 - 并将在此时结束。但这是令人困惑的代码。使用
.closest
会容易得多,因为它会找到第一个祖先匹配选择器的祖先。如果嵌套表是可能的,并且您不希望该事件向外越过所讨论的表,请在选择器字符串中包含表:
What this does is, the
target
starts at the event's target - the innermost element the event was dispatched to. Then it searches the target, then its ancestor, then its ancestor, and so on. The first one that matches the conditiontarget.tagname == 'TD'
, if any, will result inhighlight
being called and the loop ending. If no elements match, then the loop will continue until the target isthis
- the table - and will end at that point.But this is pretty confusing code. Using
.closest
would be much easier, since it will find the first ancestor matching a selector.If nested tables are a possibility, and you don't want the event to go outward past the table in question, include the table in the selector string:
在事件侦听器中,
此
等于event.currenttarget
,这是侦听器被添加到(table
)的元素。event.target
是实际单击的嵌套元素。因此,循环从单击的元素上行走dom层次结构(使用
target.parentnode
),直到到达侦听器被添加到的表为止。如果它沿途达到
td
元素,则突出显示了该元素并返回,从而突出了循环。大致相当于:
In an event listener,
this
is equivalent toevent.currentTarget
, which is the element that the listener was added to (thetable
).event.target
is the nested element that was actually clicked on.So the loop is walking up the DOM hierarchy (using
target.parentNode
) from the clicked element until it reaches the table that the listener was added to.If it reaches a
TD
element along the way, it highlights that element and returns, which breaks out of the loop.It's roughly equivalent to: