简体   繁体   English

如何在Javascript / Babel中迭代HTMLCollection

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

I am trying to set up a website using webpack and Babel. 我正在尝试使用webpack和Babel建立一个网站。 I am trying assign an "onclick" event to all of items inside of a table using jQuery. 我正在尝试使用jQuery为表中的所有项目分配“onclick”事件。 I am selecting all "clickable-row" table row items using getElementsByClassName which returns an HTMLCollection but when calling .length of it, it returns 0. Printing out the collection to console shows that there are items inside of it. 我正在使用返回HTMLCollection的getElementsByClassName选择所有“可点击行”表行项目但是当调用它的.length时,它返回0.将集合打印到控制台显示其中有项目。 Which leads me to thinking it's a Babel problem. 这让我觉得这是一个巴别塔问题。

I tried converting it to an Array - the array is empty. 我尝试将其转换为数组 - 数组为空。 Tried document.querySelectorAll(); 试过document.querySelectorAll(); which returns empty NodeList and the ... operator, tried using .forEach() and tried using HTMLCollection.prototype.forEach = Array.prototype.forEach; 返回空的NodeList和...运算符,尝试使用.forEach()并尝试使用HTMLCollection.prototype.forEach = Array.prototype.forEach; none of which lead anywhere. 没有一个领先。

Here is the code I'm using: 这是我正在使用的代码:

$('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);
}

Here is the result returned by console in google chrome: 以下是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)

I tried recreating the same thing in jsfiddle but it didn't cause the same behaviour which leads me to think even more it's a Babel/webpack thing. 我尝试在jsfiddle中重新创建相同的东西,但它没有导致相同的行为导致我更多地考虑它是​​一个Babel / webpack的东西。 http://jsfiddle.net/h2emxdf1/2/ http://jsfiddle.net/h2emxdf1/2/

Sorry if I mixed things up but I am a newbie if it comes to this whole webpack thing. 对不起,如果我把事情搞混了,但如果涉及到整个webpack的事情,我就是新手了。

Thanks to @str I realized that js executes functions asynchronously which was indeed the problem in my case. 感谢@str我意识到js异步执行函数,这确实是我的问题。 So I created a callback. 所以我创建了一个回调。 Now it works as it should be. 现在它应该工作。

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

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