我尝试使用以下代码循环遍历由 JavaScript 的 .children
属性生成的 HTMLCollection:
var articles = data.children;
var newsGrid = document.getElementById('js-news__grid');
for (var i = 0; i < articles.length; i++) {
articles[i].classList.add('loading');
newsGrid.appendChild(articles[i]);
};
data
变量是成功 XHR 的片段。当我运行循环时,它只附加第一个子元素并且循环结束,当在循环之前运行 console.log(articles);
时,它显示 2 个 HTML 元素(就像它应该的那样),但只显示长度为 1。如果我删除循环并运行 console.log(articles);
,它会像以前一样显示 2 个 HTML 元素,但现在长度为 2。
为了简单起见,我省略了 XHR 代码,因为从 data.children 生成的 HTMLCollection 看起来是正确的。以下是日志消息:
[article.news__item, article.news__item]
0: article.news__item
1: article.news__item
length: 2
__proto__: HTMLCollection
[article.news__item, article.news__item]
0: article.news__item
length: 1
__proto__: HTMLCollection
最佳答案
问题是.children是一个实时集合,当您将每个子项移出容器时,它将得到更新。
就您而言,data
有 2 个 child 所以articles.length
循环开始时为 2,但在第一次迭代之后,您重新定位了第一个子级,这意味着 articles
对象现在仅包含 1 个元素和 i
现在循环条件为 2 i < articles.length
失败。
因此一个简单的解决方案是使用反向循环
var articles = data.children;
var newsGrid = document.getElementById('js-news__grid');
for (var i = articles.length - 1; i >= 0; i--) {
articles[i].classList.add('loading');
newsGrid.appendChild(articles[i]);
};
另一个解决方案是转换 articles
到普通数组
var articles = [].slice.call(data.children);
<小时/>
RobG 建议的另一种方法是
var articles = data.children;
var newsGrid = document.getElementById('js-news__grid');
while (articles.length) {
articles[0].classList.add('loading');
newsGrid.appendChild(articles[0]);
};
关于循环时 JavaScript .children HTML 集合长度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31332013/