[英].forEach() stops after first iteration
一個簡單的.forEach()
在第一次迭代后根據內容停止......
我的初始循環如下所示:
document.getElementsByClassName("app-form-to-js").forEach(function(node) {
node.classList.remove("app-form-to-js");
jsForms[node.id]=node.cloneNode(true);
node.remove();
});
當第一個循環發生時,它並沒有超出。
然后,經過一些調整后,我設法使循環使用此代碼:
document.getElementsByClassName("app-form-to-js").forEach(function(node) {
jsForms[node.id]=node.cloneNode(true);
jsForms[node.id].classList.remove("app-form-to-js");
});
但是,當我使用node.classList.remove("app-form-to-js");
或node.remove();
在循環,
在第一次迭代后它總是會停止。
如果我改變節點,知道為什么循環在第一次迭代后停止(所以它至少迭代一次)?
document.getElementsByClassName
返回一個HTMLCollection
,它沒有forEach
的定義。 但是,您可以通過使用Array.from()
將其轉換為一個數組,該數組確實定義了一個數組,如下所示:
var collection = Array.from(document.getElementsByClassName("app-form-to-js"));
collection.forEach(function(node){...});
編輯:
正如@Preciel 向我指出的那樣,NodeList
對象確實有一個類似於數組的forEach()
函數。 如果您更願意使用它,您可以將document.getElementsByClassName("app-form-to-js")
替換為document.querySelectorAll(".app-form-to-js")
這將返回一個NodeList
而不是HTMLCollection
使用 ES6 擴展運算符創建數組的另一種方法(這是我的首選方法):
const elements = [...document.getElementsByClassName("app-form-to-js")];
elements.forEach((node)=>{...});
//OR:
elements.map((node,i)=>{... return node});
//Etc...
如果你使用 .map() 方法,你可以直接對元素進行更改,它會反映在 DOM 等中 - 非常強大的技術(記得在函數中返回修改后的節點)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.