js removeChild 障眼法 可能出现的错误
人气:0
有结构:
<ul id="demo">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
如果运行代码1:
var ul = document.getElementById('demo');
var liList = ul.getElementsByTagName('li');
for (var i = 0; i < = liList.length; i++) {
ul.removeChild(liList[i]);
}
如果和我一样被欺骗了,那么看看正确的代码就明白原因啦!
var ul = document.getElementById('demo');
var liList = ul.getElementsByTagName('li');
var lilength = liList.length;
for (var i = 0; i < lilength; i++) {
ul.removeChild(liList[0]);
}
复制代码 代码如下:
<ul id="demo">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
如果运行代码1:
复制代码 代码如下:
var ul = document.getElementById('demo');
var liList = ul.getElementsByTagName('li');
for (var i = 0; i < = liList.length; i++) {
ul.removeChild(liList[i]);
}
如果和我一样被欺骗了,那么看看正确的代码就明白原因啦!
复制代码 代码如下:
var ul = document.getElementById('demo');
var liList = ul.getElementsByTagName('li');
var lilength = liList.length;
for (var i = 0; i < lilength; i++) {
ul.removeChild(liList[0]);
}
加载全部内容