本文介绍了我无法通过JavaScript删除页面中的所有段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML5 Document</title>
<p>1
<p>2
<p>3
<p>4
<p>5
<p>6
<p>7
<p>8
<p>9
<p>10
<p>11
<p>12
<script>
// When the document is clicked, codes below should remove all the paragraphs in the page.
// There are 12 paragraphs in the page, but codes below can just remove 6 of them.
document.addEventListener('click', function () {
var i, allParagraphElements = document.getElementsByTagName('p');
console.log('allParagraphElements.length: ' + allParagraphElements.length);
for (i = 0; i < allParagraphElements.length; i += 1) {
console.log('i: ' + i);
allParagraphElements[i].parentNode.removeChild(allParagraphElements[i]);
}
}, false);
</script>
请参阅jsFiddle上的代码:
See codes on jsFiddle: http://jsfiddle.net/7NmRh
我如何解决这个问题?谢谢。
How can I fix this problem? Thank you.
推荐答案
您从上到下迭代:
迭代一:
十二段落,索引= 0
Iteration one:twelve paragraphs, index = 0
索引0的段落被删除,第1段现在处于索引0
paragraph at index 0 is deleted and paragraph 1 is now at index 0
第二次迭代:
十一段,index = 1
Second iteration:Eleven paragraphs, index = 1
段索引1被删除,第2段现在是索引1
paragraph at index 1 is deleted and paragraph 2 is now at index 1
你看到了什么问题?你只删除一半段落
You see what's going wrong? You only delete half of the paragraphs
反之亦然,删除所有段落
Iterate the other way around and all the paragraphs are deleted
这篇关于我无法通过JavaScript删除页面中的所有段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!