循环时JavaScript.children HTML集合长度问题 [英] JavaScript .children HTML collection length issues when looping

查看:255
本文介绍了循环时JavaScript.children HTML集合长度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码遍历从JavaScript的 .children 属性生成的HTMLCollection:

I'm attempting to loop through an HTMLCollection produced from JavaScript's .children property using the following code:

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]);
};

数据变量是一个片段成功的XHR。当我运行循环时,它只附加第一个子节点并且循环结束,并且在循环之前运行 console.log(articles); 时,它显示2个HTML元素(它应该)但只有1的长度。如果我删除循环并运行 console.log(文章); 它显示像以前一样的2个HTML元素,但它现在的长度为2.

The data variable is a fragment of a successful XHR. When I run the loop, it only appends the first child and the loop ends, and when running console.log(articles); before the loop, it shows 2 HTML elements (like it should) but only has a length of 1. If I remove the loop and run console.log(articles); it shows the 2 HTML elements like before, BUT it now has a length of 2.

为了简单起见,我遗漏了我的XHR代码,因为从data.children生成的HTMLCollection看起来不错。以下是日志消息:

I've left out my XHR code for the sake of simplicity and due to the fact that the HTMLCollection that is produced from data.children looks correct. Here are the log messages:

[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 是一个真人收藏,当你将每个孩子从容器中移出时会更新。

The problem is .children is a live collection, which will get updated as you move each child out of the container.

在你的情况下,数据有2个孩子所以 articles.length 在循环开始时是2,但是在第一次迭代后你重新定位了第一个孩子,这意味着文章对象现在只包含1个元素, i 现在是2,循环条件 i< articles.length 失败。

In your case, there are 2 children for data so articles.length is 2 when the loop is started, but after the first iteration you have relocated the first child which means the articles object is now contains only 1 element and i is 2 now the loop condition i < articles.length fails.

所以一个简单的解决方案是使用反向循环

So one easy solution is to use a reverse loop

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]);
};

另一个解决方案是转换文章到正常数组

Another solution will be is to convert articles to a normal array

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集合长度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆