<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)
};
答案 0 :(得分:5)
阅读while
<强> 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
中没有第一个孩子。循环条件失败。