uni-app 中获取悬停 li 元素的下标
- Item 1
- Item 2
- Item 3
const lis = Array.from(document.querySelectorAll('li'));
lis.forEach(li => {
li.addEventListener('mouseenter', () => {
const index = lis.indexOf(li);
console.log('Hovered on li at index ' + index);
});
});
步骤:
- 获取所有 li 元素的 NodeList 对象,可以使用
document.querySelectorAll('li')方法。 - 将 NodeList 对象转换为数组,可以使用
Array.from()方法或者Array.prototype.slice.call()方法。 - 遍历数组,使用
Array.prototype.indexOf()方法获取当前 li 元素在数组中的下标。
原文地址: https://www.cveoy.top/t/topic/lHhu 著作权归作者所有。请勿转载和采集!