场景
当使用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';})};
},