admin管理员组文章数量:1419228
Why does the author of Test-Driven JavaScript Development (Christian Johansen) use the while
statement instead of the if
statement in the code below?
function getEventTarget(event) {
var target = event.target || event.srcElement;
while (target && target.nodeType != 1) {
target = target.parentNode;
}
return target;
}
Why does the author of Test-Driven JavaScript Development (Christian Johansen) use the while
statement instead of the if
statement in the code below?
function getEventTarget(event) {
var target = event.target || event.srcElement;
while (target && target.nodeType != 1) {
target = target.parentNode;
}
return target;
}
Share
Improve this question
edited Feb 24, 2012 at 4:33
Michael Petrotta
61k27 gold badges152 silver badges181 bronze badges
asked Feb 24, 2012 at 4:30
DathanDathan
1,1651 gold badge10 silver badges11 bronze badges
1
-
4
You do realize that
while
is a loop, right? It will execute over and over until the condition bees false. – Gabe Commented Feb 24, 2012 at 4:34
2 Answers
Reset to default 9Because the author wanted to keep walking up the tree until the correct node type was found; it might not be the immediate parent.
However, in this case it makes no sense, as parentNode
will always return an element in real-world usage (or a Document).
Because he is walking up..
If you see pretty well, in the loop he is assigning the target again with its parent and the parent is not nodetype 1
target = target.parentNode;
I don't know what is he trying or what is the purpose or the goal but it's quite simple..
Imagine the DOM
<div>
<div>
<div>
<div>
Imagine he starts from here.. he will always get the max parent with not nodetype 1 the hightes parent so the first div..
</div>
</div>
</div>
</div>
SO basically. He is getting the Higher parent ... That's why is he looping.. if uses the If.. he will get just the First parent
本文标签: If vs while in specific JavaScript codeStack Overflow
版权声明:本文标题:If vs. while in specific JavaScript code - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745302606a2652463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论