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

鼠标事件触发时如何获取对应元素在NodeList中的准确索引位置

实现方案

有两种常用实现方式,按需选择即可:


方法1:遍历绑定索引(性能最优)

遍历NodeList时直接通过forEach的索引参数绑定对应位置,触发事件时直接调用即可,无需额外计算:

const articles = document.querySelectorAll(".articles");
// forEach的第二个参数即为当前元素在NodeList中的索引(从0开始计数)
articles.forEach((article, index) => {
  article.addEventListener('mouseenter', () => {
    console.log(`当前悬浮元素索引:${index}`, articles[index]);
  });
});

方法2:事件触发时动态计算索引

如果不想在绑定阶段存储索引,可以在事件触发时实时查找当前元素的位置:

const articles = document.querySelectorAll(".articles");
for (const x of articles) {
  x.addEventListener('mouseenter', (e) => {
    // 将NodeList转为数组后查找当前触发事件元素的索引
    const currentIndex = Array.from(articles).indexOf(e.currentTarget);
    console.log(articles[currentIndex]);
  });
}

注:document.querySelectorAll返回的是静态NodeList,若后续DOM中有.articles元素增删,需要重新执行查询获取最新集合,否则索引会和实际DOM结构不匹配。

内容的提问来源于stack exchange,提问作者ZBop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:15:02