You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在遍历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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 01:24:04