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
Add a ment  | 

2 Answers 2

Reset to default 9

Because 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