如何在遍历box节点的forEach()方法中循环处理选中的link元素
实现方案
你当前的场景下不需要全局遍历所有.link元素,你之前全局选中所有link后没有区分和box的对应关系,才需要额外做索引匹配,其实直接操作当前hover的.box内部对应的.link即可,逻辑更简洁也不会误操作其他box的link,修改后的JS代码如下:
const box = document.querySelectorAll('.box') box.forEach((singleBox) => { // 查找当前box内部的link元素 const currentLink = singleBox.querySelector('.link') singleBox.addEventListener("mouseenter", () => { currentLink.classList.add('top'); }); singleBox.addEventListener("mouseleave", () => { currentLink.classList.remove("top"); }); });
如果你确实有需要遍历所有.link节点的场景,直接对querySelectorAll返回的NodeList调用forEach方法即可,示例如下:
const allLinks = document.querySelectorAll('.link') // 遍历所有link节点执行操作 allLinks.forEach(linkItem => { linkItem.classList.add('top') })
内容的提问来源于stack exchange,提问作者Ali Shour
相关产品推荐
相关产品推荐

