簡體   English   中英

HTMLCollection的長度為8,但記錄其任何索引是否返回未定義?

[英]HTMLCollection's length is 8 but logging any of its indices returns undefined?

我正在嘗試遍歷HTMLCollection,但看起來好像在進入循環之前滿足了中斷條件。 此外,當我將HTMLCollection打印到控制台時,它返回HTMLCollection並且可以看到其中包含元素,但是,當我嘗試打印其任何索引時,它都返回undefined

這是代碼:

var applicant_elements = document.getElementsByClassName('applicant');
console.log(applicant_elements); // returns the HTMLCollection
                                 // with length of 8
                                 // and valid elements
console.log(applicant_elements[0]); // returns undefined
for (var i = 0; i < applicant_elements.length; i++) {
    console.log('hello'); // this is never logged
}

這是上面的代碼記錄的內容:

控制台日志屏幕截圖

我還應該指出,我正在angularJS控制器中運行以下代碼。 不知道這是否會改變任何東西,但是我覺得不應該改變

該答案所述console.log()調用不一定在不同的瀏覽器中立即進行。 document.getElementsByClassName返回對實時 HTMLCollection的引用。 這意味着對DOM的任何更改將自動反映在集合中,因此,在最終解決console.log的調用后,您將在輸出中看到所有關聯的節點。 但是,對applicant_elements[0]引用不是實時引用,它是在給定的時間點解析的,因此不會因未定義而改變。

總結一下:查詢之后,您的HTMLCollection可能為空,但是您的代碼在console.log()調用解析之前(例如,從函數返回之前console.log()添加了元素。

getElementsByClassName的有趣之處在於它是一個實時html集合。 因此,這意味着要對其進行添加和刪除。 並在控制台中添加了您懶惰的評估,這使調試變得很有趣。

 var x = document.getElementsByClassName("test"); console.log("before", x.length); // will show 0 console.log(x); // In browser console will show one item because of code below var d = document.createElement("div"); //create an element to add d.classList.add("test") // our class we are looking for document.body.appendChild(d); // add it console.log("after", x.length); // will show 1 console.log(x); //will show 1 item 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM