javascript - 如何获取所选类名的索引?
问题描述
我有多个input
字段分配给特定的类名。现在我想获取input
字段的类名的索引和console.log()
它。
这是我的代码:
document.querySelectorAll('.class-name').forEach(item => {
item.addEventListener('change', event => {
console.log(item); //print the index of the item
})
})
我怎样才能做到这一点?请帮我。
解决方案
该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>
推荐阅读
- vue.js - Div(包含项目列表)在外部单击时不关闭
- javascript - 在 Vue.js 组件中使用 D3 鼠标事件坐标
- android - 如何调整布局中的水平条形图?
- python - 使用 np.random.choice() 生成样本的快速方法?
- c# - 哪个更快:String、BigInteger 或 Guid 用于字典键?
- python - 二分搜索算法接受不在数据集中的数据
- kubernetes - apiserver 可以通过 CNI 提供的网络连接到节点的 Kubelet 端口吗?
- javascript - 根据下拉列表中选择的值自动填充文本框
- pipeline - Snakemake 报错:Missing input files for rule all
- rest - Microsoft Azure 中的 Web App 服务能否访问第三方 REST API?