鼠标事件触发时如何获取对应元素在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
相关产品推荐
相关产品推荐

