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)
};
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
我似乎无法理解此while
语句如何删除上述列表中的所有节点。有人可以解释一下吗?
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
边读边读
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 循环条件失败。