如果与特定JavaScript代码相对

时间:2012-02-24 04:30:30

标签: javascript

为什么测试驱动的JavaScript开发(Christian Johansen)的作者在下面的代码中使用while语句而不是if语句?

function getEventTarget(event) {
    var target = event.target || event.srcElement;

    while (target && target.nodeType != 1) {
        target = target.parentNode;
    }

    return target;
}

2 个答案:

答案 0 :(得分:9)

因为作者想继续走树,直到找到正确的节点类型;它可能不是直接的父母。

但是,在这种情况下没有任何意义,因为parentNode将始终返回实际使用(或文档)中的元素。

答案 1 :(得分:0)

因为他正在走路......

如果你看得很清楚,他会在循环中再次使用其父级分配目标,而父级不是nodetype 1

 target = target.parentNode;

我不知道他在尝试什么,目的或目标是什么,但这很简单..

想象一下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>
基本上是这样的。他正在接受更高父母...这就是为什么他会循环...如果使用If ..他将只获得第一个父母