【问题标题】:JavaScript .children HTML collection length issues when looping循环时的 JavaScript .children HTML 集合长度问题
【发布时间】:2015-07-10 03:33:33
【问题描述】:

我正在尝试使用以下代码循环通过 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

【问题讨论】:

    标签: javascript loops xmlhttprequest children


    【解决方案1】:

    问题是.children 是一个实时集合,当您将每个孩子移出容器时,它会更新。

    在您的情况下,data 有 2 个子对象,因此循环开始时articles.length 为 2,但在第一次迭代后,您已重新定位第一个子对象,这意味着 articles 对象现在仅包含 1元素和i 为2 现在循环条件i &lt; 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]);
    };
    

    【讨论】:

    • 或者使用while循环:while (articles.length) newsGrid.appendChild(articles[0]);。在 IE8 及更低版本中,使用 slice 从集合创建数组将失败,它不允许将宿主对象作为 this 传递给内置方法。 ;-)
    • @RobG 是的...谢谢...在答案中也更新了while 选项
    猜你喜欢
    • 2018-05-31
    • 2015-07-24
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多