場景
當使用document.getElementsByClassName方法獲取一個包含DOM節點的集合arr時,正常的forEach和map操作都會報一個arr.map is not a function的錯誤
因為這里的arr并不是標準的 數組 (Array),而是一個 HTMLCollection
解決
- 使用document.querySelectorAll獲取節點列表
- 轉為數組
Array.from(arr).forEach(v => {v.childNodes[0].style.display = 'none';
});
- 擴展運算符
[...arr].forEach(v => {v.childNodes[0].style.display = 'none';
});
- 用傳統 for 循環
for (let i = 0; i < arr.length; i++) {arr[i].childNodes[0].style.display = 'none';
}
拓展
- 這是一個右擊出現彈窗的事件,每個節點都對應一個彈窗,可左鍵一鍵清空
handleRightClickPoint(index, e){e.preventDefault();let t = document.getElementsByClassName('hangdian-right')let totalnodes = t[index].childNodestotalnodes[0].style.display = 'block';totalnodes[0].style.left = (e.clientX + 18) + 'px';totalnodes[0].style.top = (e.clientY - 5) + 'px';totalnodes[0].onclick = function() {totalnodes[0].style.display = 'none';};document.onclick = function() {[...t].forEach(v=>{v.childNodes[0].style.display = 'none';})};
},