请解释此javaScript代码如何删除所有节点

时间:2013-10-15 01:14:39

标签: javascript html html5 while-loop removechild

HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

我似乎无法理解这个while语句如何删除上面列表中的所有节点。有人可以解释一下吗?

的JavaScript

while(myList.firstChild) {
    myList.removeChild(myList.firstChild)
};

1 个答案:

答案 0 :(得分:5)

阅读while

enter image description here

<强> HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

js代码

while(myList.firstChild) // loop will run while myList has a firstChild
    {myList.removeChild(myList.firstChild)
};

运行时间

1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.

现在HTML

<ul id="myList">
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

运行

2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.

现在HTML

<ul id="myList">
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

运行

3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.

现在HTML

<ul id="myList">
   <li>Item 4</li>
</ul>

运行

4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.

现在HTML

<ul id="myList">
</ul>

运行

js代码无法运行,因为myList中没有第一个孩子。循环条件失败。