首页 > 解决方案 > 如何获取所选类名的索引?

问题描述

我有多个input字段分配给特定的类名。现在我想获取input字段的类名的索引和console.log()它。

这是我的代码:

document.querySelectorAll('.class-name').forEach(item => {
    item.addEventListener('change', event => {
        console.log(item); //print the index of the item
    })
})

我怎样才能做到这一点?请帮我。

标签: javascript

解决方案


forEach()函数允许定义一个索引变量以跟踪每个项目的索引。由于index变量在从 eventListener 调用时保持其上下文,因此您可以使用它来获取索引号:

document.querySelectorAll('.class-name').forEach((item, index) => {   // Here define the index variable
    item.addEventListener('click', event => {
        console.log(index); //print the index of the item
    })
})
<button class="class-name">Click index 0</button>
<button class="class-name">Click index 1</button>
<button class="class-name">Click index 2</button>


推荐阅读