如何使用.indexOf获取NodeList中事件目标元素的索引?
NodeList能不能用.indexOf()?答案是不行,这就是你报错的原因
document.querySelectorAll()返回的是NodeList,这是个类数组对象,不是真正的数组,而indexOf()是数组专属的方法,NodeList原型上根本没有这个方法,所以直接调用会抛出TypeError: divs.indexOf is not a function的错误。
下面给你几种解决办法:
办法1:把NodeList转成数组
用Array.from()或者扩展运算符[...]转成真正的数组,之后就能正常调用indexOf()了:
const divs = Array.from(document.querySelectorAll('div')); // 也可以写成:const divs = [...document.querySelectorAll('div')]; function isFirst(event) { console.log(event.target == divs[0]); console.log(divs.indexOf(event.target)); // 正常返回元素索引,找不到则返回-1 } divs.forEach(e => e.addEventListener('click', isFirst));
办法2:直接借用数组的indexOf方法
不需要转数组,通过call方法改变数组indexOf的执行上下文,让它作用在NodeList上:
const divs = document.querySelectorAll('div'); function isFirst(event) { console.log(event.target == divs[0]); console.log(Array.prototype.indexOf.call(divs, event.target)); } divs.forEach(e => e.addEventListener('click', isFirst));
办法3:绑定事件时直接记录索引
最省事的方式,在遍历绑定事件的过程中,直接把当前元素的索引传递给事件处理函数,不用后续再查找:
const divs = document.querySelectorAll('div'); function isFirst(index, event) { console.log(event.target == divs[0]); console.log(index); // 直接拿到当前点击元素的索引 } divs.forEach((e, index) => { e.addEventListener('click', (event) => isFirst(index, event)); });
内容的提问来源于stack exchange,提问作者Miu
相关产品推荐
相关产品推荐

