簡體   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