繁体   English   中英

如何在Javascript / Babel中迭代HTMLCollection

[英]How to iterate through HTMLCollection in Javascript/Babel

我正在尝试使用webpack和Babel建立一个网站。 我正在尝试使用jQuery为表中的所有项目分配“onclick”事件。 我正在使用返回HTMLCollection的getElementsByClassName选择所有“可点击行”表行项目但是当调用它的.length时,它返回0.将集合打印到控制台显示其中有项目。 这让我觉得这是一个巴别塔问题。

我尝试将其转换为数组 - 数组为空。 试过document.querySelectorAll(); 返回空的NodeList和...运算符,尝试使用.forEach()并尝试使用HTMLCollection.prototype.forEach = Array.prototype.forEach; 没有一个领先。

这是我正在使用的代码:

$('document').ready(getTableRows);

function getTableRows() {
    let tableRows = document.getElementsByClassName("clickable-row");
    console.log(tableRows);
    console.log("Length of this collection = " + tableRows.length);
    let array = Array.from(tableRows);
    console.log("Converted to array");
    console.log(array);
}

以下是Google Chrome中控制台返回的结果:

HTMLCollection []
    0: tr.clickable-row
    1: tr.clickable-row
    2: tr.clickable-row
    3: tr.clickable-row
    4: tr.clickable-row
    5: tr.clickable-row
    6: tr.clickable-row
    7: tr.clickable-row
    8: tr.clickable-row
    9: tr.clickable-row
    length: 10
    __proto__: HTMLCollection

Length of this collection = 0

Converted to array
[]
    length: 0
    __proto__: Array(0)

我尝试在jsfiddle中重新创建相同的东西,但它没有导致相同的行为导致我更多地考虑它是​​一个Babel / webpack的东西。 http://jsfiddle.net/h2emxdf1/2/

对不起,如果我把事情搞混了,但如果涉及到整个webpack的事情,我就是新手了。

感谢@str我意识到js异步执行函数,这确实是我的问题。 所以我创建了一个回调。 现在它应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM