循环时 JavaScript .children HTML 集合长度问题

标签 javascript loops xmlhttprequest children

我尝试使用以下代码循环遍历由 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/

相关文章:

javascript - d3js : how to put circles at the end of an arc

javascript - JS 将单个索引中的 2 个数组及其各个值合并到 1 个数组中的单个索引中

javascript - 学校元素 - 带有图钉和 onclick 事件的 IMG

php - 尝试从 formData 上传大文件

ajax - 为什么 XMLHttpRequest 规范会阻止设置 Accept-Encoding header ?

javascript - Rails 4 turbo-link 阻止 jQuery 脚本工作

java - For-Each 循环中的限制

PHP - 打印乘法表的最佳方式

Scala - 每个循环之间的区别

angularjs - XMLHttpRequest 无法加载 .... 预检响应具有无效的 HTTP 状态代码 401