-2

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)
};
4

1 回答 1

5

边读边

在此处输入图像描述

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. While 循环条件失败。

于 2013-10-15T01:35:31.690 回答