我有以下代码。当我尝试删除所有图像时,只有3个被删除。感觉很奇怪。这是什么原因?
<script type="text/javascript">
function c() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].parentNode.removeChild(images[i]) //or images[i].remove()
}
}
</script>
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<input id="clickMe" type="button" value="Delete Images" onclick="c()" />
答案 0 :(得分:1)
您需要以相反的顺序循环。如果向前循环,则在删除元素时,您正在修改剩余元素的索引。所以,请改为:
for (var i = images.length - 1; i >= 0; i--) {
// Remove first element (at [0]) repeatedly
images[0].parentNode.removeChild(images[0]);
}
答案 1 :(得分:1)
只需使用while循环
<script type="text/javascript">
function c() {
var images = document.getElementsByTagName('img');
var counter = 0;
while(images.length){
images[counter].parentNode.removeChild(images[counter])
}
}
</script>
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<input id="clickMe" type="button" value="Delete Images" onclick="c()" />
答案 2 :(得分:-1)
function c() {
var images = document.getElementsByTagName('img');
for (var i = images.length-1; i > -1; i--) {
images[i].parentNode.removeChild(images[i]) //or images[i].remove()
}
}
function c1() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].parentNode.removeChild(images[i]) //or images[i].remove();
//you can also decrement i by one with each delete, more than one way to skin a cat as they say.
i--;
}
}
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<img src="http://unsplash.it/200/300/" />
<input id="clickMe" type="button" value="Delete Images" onclick="c1()" />
要同意我的评论,您也可以向后迭代以避免在每次迭代时调整i。
for (var i = images.length-1; i >-1; i--) {
images[i].parentNode.removeChild(images[i]) //or images[i].remove()
}